id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
164,100
nats-io/gnatsd
server/server.go
NumClients
func (s *Server) NumClients() int { s.mu.Lock() defer s.mu.Unlock() return len(s.clients) }
go
func (s *Server) NumClients() int { s.mu.Lock() defer s.mu.Unlock() return len(s.clients) }
[ "func", "(", "s", "*", "Server", ")", "NumClients", "(", ")", "int", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "len", "(", "s", ".", "clients", ")", "\n", "}" ]
// NumClients will report the number of registered clients.
[ "NumClients", "will", "report", "the", "number", "of", "registered", "clients", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1774-L1778
164,101
nats-io/gnatsd
server/server.go
getClient
func (s *Server) getClient(cid uint64) *client { s.mu.Lock() defer s.mu.Unlock() return s.clients[cid] }
go
func (s *Server) getClient(cid uint64) *client { s.mu.Lock() defer s.mu.Unlock() return s.clients[cid] }
[ "func", "(", "s", "*", "Server", ")", "getClient", "(", "cid", "uint64", ")", "*", "client", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "clients", "[", "cid", "]", "\n", "}" ]
// getClient will return the client associated with cid.
[ "getClient", "will", "return", "the", "client", "associated", "with", "cid", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1786-L1790
164,102
nats-io/gnatsd
server/server.go
NumSubscriptions
func (s *Server) NumSubscriptions() uint32 { s.mu.Lock() defer s.mu.Unlock() return s.numSubscriptions() }
go
func (s *Server) NumSubscriptions() uint32 { s.mu.Lock() defer s.mu.Unlock() return s.numSubscriptions() }
[ "func", "(", "s", "*", "Server", ")", "NumSubscriptions", "(", ")", "uint32", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "numSubscriptions", "(", ")", "\n", "}" ]
// NumSubscriptions will report how many subscriptions are active.
[ "NumSubscriptions", "will", "report", "how", "many", "subscriptions", "are", "active", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1799-L1803
164,103
nats-io/gnatsd
server/server.go
numSubscriptions
func (s *Server) numSubscriptions() uint32 { var subs int s.accounts.Range(func(k, v interface{}) bool { acc := v.(*Account) if acc.sl != nil { subs += acc.TotalSubs() } return true }) return uint32(subs) }
go
func (s *Server) numSubscriptions() uint32 { var subs int s.accounts.Range(func(k, v interface{}) bool { acc := v.(*Account) if acc.sl != nil { subs += acc.TotalSubs() } return true }) return uint32(subs) }
[ "func", "(", "s", "*", "Server", ")", "numSubscriptions", "(", ")", "uint32", "{", "var", "subs", "int", "\n", "s", ".", "accounts", ".", "Range", "(", "func", "(", "k", ",", "v", "interface", "{", "}", ")", "bool", "{", "acc", ":=", "v", ".", "(", "*", "Account", ")", "\n", "if", "acc", ".", "sl", "!=", "nil", "{", "subs", "+=", "acc", ".", "TotalSubs", "(", ")", "\n", "}", "\n", "return", "true", "\n", "}", ")", "\n", "return", "uint32", "(", "subs", ")", "\n", "}" ]
// numSubscriptions will report how many subscriptions are active. // Lock should be held.
[ "numSubscriptions", "will", "report", "how", "many", "subscriptions", "are", "active", ".", "Lock", "should", "be", "held", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1807-L1817
164,104
nats-io/gnatsd
server/server.go
ConfigTime
func (s *Server) ConfigTime() time.Time { s.mu.Lock() defer s.mu.Unlock() return s.configTime }
go
func (s *Server) ConfigTime() time.Time { s.mu.Lock() defer s.mu.Unlock() return s.configTime }
[ "func", "(", "s", "*", "Server", ")", "ConfigTime", "(", ")", "time", ".", "Time", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "configTime", "\n", "}" ]
// ConfigTime will report the last time the server configuration was loaded.
[ "ConfigTime", "will", "report", "the", "last", "time", "the", "server", "configuration", "was", "loaded", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1825-L1829
164,105
nats-io/gnatsd
server/server.go
Addr
func (s *Server) Addr() net.Addr { s.mu.Lock() defer s.mu.Unlock() if s.listener == nil { return nil } return s.listener.Addr() }
go
func (s *Server) Addr() net.Addr { s.mu.Lock() defer s.mu.Unlock() if s.listener == nil { return nil } return s.listener.Addr() }
[ "func", "(", "s", "*", "Server", ")", "Addr", "(", ")", "net", ".", "Addr", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "listener", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "s", ".", "listener", ".", "Addr", "(", ")", "\n", "}" ]
// Addr will return the net.Addr object for the current listener.
[ "Addr", "will", "return", "the", "net", ".", "Addr", "object", "for", "the", "current", "listener", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1832-L1839
164,106
nats-io/gnatsd
server/server.go
MonitorAddr
func (s *Server) MonitorAddr() *net.TCPAddr { s.mu.Lock() defer s.mu.Unlock() if s.http == nil { return nil } return s.http.Addr().(*net.TCPAddr) }
go
func (s *Server) MonitorAddr() *net.TCPAddr { s.mu.Lock() defer s.mu.Unlock() if s.http == nil { return nil } return s.http.Addr().(*net.TCPAddr) }
[ "func", "(", "s", "*", "Server", ")", "MonitorAddr", "(", ")", "*", "net", ".", "TCPAddr", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "http", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "s", ".", "http", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", "\n", "}" ]
// MonitorAddr will return the net.Addr object for the monitoring listener.
[ "MonitorAddr", "will", "return", "the", "net", ".", "Addr", "object", "for", "the", "monitoring", "listener", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1842-L1849
164,107
nats-io/gnatsd
server/server.go
ClusterAddr
func (s *Server) ClusterAddr() *net.TCPAddr { s.mu.Lock() defer s.mu.Unlock() if s.routeListener == nil { return nil } return s.routeListener.Addr().(*net.TCPAddr) }
go
func (s *Server) ClusterAddr() *net.TCPAddr { s.mu.Lock() defer s.mu.Unlock() if s.routeListener == nil { return nil } return s.routeListener.Addr().(*net.TCPAddr) }
[ "func", "(", "s", "*", "Server", ")", "ClusterAddr", "(", ")", "*", "net", ".", "TCPAddr", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "routeListener", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "s", ".", "routeListener", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", "\n", "}" ]
// ClusterAddr returns the net.Addr object for the route listener.
[ "ClusterAddr", "returns", "the", "net", ".", "Addr", "object", "for", "the", "route", "listener", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1852-L1859
164,108
nats-io/gnatsd
server/server.go
ProfilerAddr
func (s *Server) ProfilerAddr() *net.TCPAddr { s.mu.Lock() defer s.mu.Unlock() if s.profiler == nil { return nil } return s.profiler.Addr().(*net.TCPAddr) }
go
func (s *Server) ProfilerAddr() *net.TCPAddr { s.mu.Lock() defer s.mu.Unlock() if s.profiler == nil { return nil } return s.profiler.Addr().(*net.TCPAddr) }
[ "func", "(", "s", "*", "Server", ")", "ProfilerAddr", "(", ")", "*", "net", ".", "TCPAddr", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "profiler", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "s", ".", "profiler", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", "\n", "}" ]
// ProfilerAddr returns the net.Addr object for the route listener.
[ "ProfilerAddr", "returns", "the", "net", ".", "Addr", "object", "for", "the", "route", "listener", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1862-L1869
164,109
nats-io/gnatsd
server/server.go
ReadyForConnections
func (s *Server) ReadyForConnections(dur time.Duration) bool { // Snapshot server options. opts := s.getOpts() end := time.Now().Add(dur) for time.Now().Before(end) { s.mu.Lock() ok := s.listener != nil && (opts.Cluster.Port == 0 || s.routeListener != nil) && (opts.Gateway.Name == "" || s.gatewayListener != nil) s.mu.Unlock() if ok { return true } time.Sleep(25 * time.Millisecond) } return false }
go
func (s *Server) ReadyForConnections(dur time.Duration) bool { // Snapshot server options. opts := s.getOpts() end := time.Now().Add(dur) for time.Now().Before(end) { s.mu.Lock() ok := s.listener != nil && (opts.Cluster.Port == 0 || s.routeListener != nil) && (opts.Gateway.Name == "" || s.gatewayListener != nil) s.mu.Unlock() if ok { return true } time.Sleep(25 * time.Millisecond) } return false }
[ "func", "(", "s", "*", "Server", ")", "ReadyForConnections", "(", "dur", "time", ".", "Duration", ")", "bool", "{", "// Snapshot server options.", "opts", ":=", "s", ".", "getOpts", "(", ")", "\n\n", "end", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "dur", ")", "\n", "for", "time", ".", "Now", "(", ")", ".", "Before", "(", "end", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "ok", ":=", "s", ".", "listener", "!=", "nil", "&&", "(", "opts", ".", "Cluster", ".", "Port", "==", "0", "||", "s", ".", "routeListener", "!=", "nil", ")", "&&", "(", "opts", ".", "Gateway", ".", "Name", "==", "\"", "\"", "||", "s", ".", "gatewayListener", "!=", "nil", ")", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "ok", "{", "return", "true", "\n", "}", "\n", "time", ".", "Sleep", "(", "25", "*", "time", ".", "Millisecond", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// ReadyForConnections returns `true` if the server is ready to accept clients // and, if routing is enabled, route connections. If after the duration // `dur` the server is still not ready, returns `false`.
[ "ReadyForConnections", "returns", "true", "if", "the", "server", "is", "ready", "to", "accept", "clients", "and", "if", "routing", "is", "enabled", "route", "connections", ".", "If", "after", "the", "duration", "dur", "the", "server", "is", "still", "not", "ready", "returns", "false", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1874-L1889
164,110
nats-io/gnatsd
server/server.go
ID
func (s *Server) ID() string { s.mu.Lock() defer s.mu.Unlock() return s.info.ID }
go
func (s *Server) ID() string { s.mu.Lock() defer s.mu.Unlock() return s.info.ID }
[ "func", "(", "s", "*", "Server", ")", "ID", "(", ")", "string", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "info", ".", "ID", "\n", "}" ]
// ID returns the server's ID
[ "ID", "returns", "the", "server", "s", "ID" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1892-L1896
164,111
nats-io/gnatsd
server/server.go
getClientConnectURLs
func (s *Server) getClientConnectURLs() []string { // Snapshot server options. opts := s.getOpts() urls := make([]string, 0, 1) // short circuit if client advertise is set if opts.ClientAdvertise != "" { // just use the info host/port. This is updated in s.New() urls = append(urls, net.JoinHostPort(s.info.Host, strconv.Itoa(s.info.Port))) } else { sPort := strconv.Itoa(opts.Port) _, ips, err := s.getNonLocalIPsIfHostIsIPAny(opts.Host, true) for _, ip := range ips { urls = append(urls, net.JoinHostPort(ip, sPort)) } if err != nil || len(urls) == 0 { // We are here if s.opts.Host is not "0.0.0.0" nor "::", or if for some // reason we could not add any URL in the loop above. // We had a case where a Windows VM was hosed and would have err == nil // and not add any address in the array in the loop above, and we // ended-up returning 0.0.0.0, which is problematic for Windows clients. // Check for 0.0.0.0 or :: specifically, and ignore if that's the case. if opts.Host == "0.0.0.0" || opts.Host == "::" { s.Errorf("Address %q can not be resolved properly", opts.Host) } else { urls = append(urls, net.JoinHostPort(opts.Host, sPort)) } } } return urls }
go
func (s *Server) getClientConnectURLs() []string { // Snapshot server options. opts := s.getOpts() urls := make([]string, 0, 1) // short circuit if client advertise is set if opts.ClientAdvertise != "" { // just use the info host/port. This is updated in s.New() urls = append(urls, net.JoinHostPort(s.info.Host, strconv.Itoa(s.info.Port))) } else { sPort := strconv.Itoa(opts.Port) _, ips, err := s.getNonLocalIPsIfHostIsIPAny(opts.Host, true) for _, ip := range ips { urls = append(urls, net.JoinHostPort(ip, sPort)) } if err != nil || len(urls) == 0 { // We are here if s.opts.Host is not "0.0.0.0" nor "::", or if for some // reason we could not add any URL in the loop above. // We had a case where a Windows VM was hosed and would have err == nil // and not add any address in the array in the loop above, and we // ended-up returning 0.0.0.0, which is problematic for Windows clients. // Check for 0.0.0.0 or :: specifically, and ignore if that's the case. if opts.Host == "0.0.0.0" || opts.Host == "::" { s.Errorf("Address %q can not be resolved properly", opts.Host) } else { urls = append(urls, net.JoinHostPort(opts.Host, sPort)) } } } return urls }
[ "func", "(", "s", "*", "Server", ")", "getClientConnectURLs", "(", ")", "[", "]", "string", "{", "// Snapshot server options.", "opts", ":=", "s", ".", "getOpts", "(", ")", "\n\n", "urls", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "1", ")", "\n\n", "// short circuit if client advertise is set", "if", "opts", ".", "ClientAdvertise", "!=", "\"", "\"", "{", "// just use the info host/port. This is updated in s.New()", "urls", "=", "append", "(", "urls", ",", "net", ".", "JoinHostPort", "(", "s", ".", "info", ".", "Host", ",", "strconv", ".", "Itoa", "(", "s", ".", "info", ".", "Port", ")", ")", ")", "\n", "}", "else", "{", "sPort", ":=", "strconv", ".", "Itoa", "(", "opts", ".", "Port", ")", "\n", "_", ",", "ips", ",", "err", ":=", "s", ".", "getNonLocalIPsIfHostIsIPAny", "(", "opts", ".", "Host", ",", "true", ")", "\n", "for", "_", ",", "ip", ":=", "range", "ips", "{", "urls", "=", "append", "(", "urls", ",", "net", ".", "JoinHostPort", "(", "ip", ",", "sPort", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "||", "len", "(", "urls", ")", "==", "0", "{", "// We are here if s.opts.Host is not \"0.0.0.0\" nor \"::\", or if for some", "// reason we could not add any URL in the loop above.", "// We had a case where a Windows VM was hosed and would have err == nil", "// and not add any address in the array in the loop above, and we", "// ended-up returning 0.0.0.0, which is problematic for Windows clients.", "// Check for 0.0.0.0 or :: specifically, and ignore if that's the case.", "if", "opts", ".", "Host", "==", "\"", "\"", "||", "opts", ".", "Host", "==", "\"", "\"", "{", "s", ".", "Errorf", "(", "\"", "\"", ",", "opts", ".", "Host", ")", "\n", "}", "else", "{", "urls", "=", "append", "(", "urls", ",", "net", ".", "JoinHostPort", "(", "opts", ".", "Host", ",", "sPort", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "urls", "\n", "}" ]
// getClientConnectURLs returns suitable URLs for clients to connect to the listen // port based on the server options' Host and Port. If the Host corresponds to // "any" interfaces, this call returns the list of resolved IP addresses. // If ClientAdvertise is set, returns the client advertise host and port. // The server lock is assumed held on entry.
[ "getClientConnectURLs", "returns", "suitable", "URLs", "for", "clients", "to", "connect", "to", "the", "listen", "port", "based", "on", "the", "server", "options", "Host", "and", "Port", ".", "If", "the", "Host", "corresponds", "to", "any", "interfaces", "this", "call", "returns", "the", "list", "of", "resolved", "IP", "addresses", ".", "If", "ClientAdvertise", "is", "set", "returns", "the", "client", "advertise", "host", "and", "port", ".", "The", "server", "lock", "is", "assumed", "held", "on", "entry", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1930-L1961
164,112
nats-io/gnatsd
server/server.go
resolveHostPorts
func resolveHostPorts(addr net.Listener) []string { hostPorts := make([]string, 0) hp := addr.Addr().(*net.TCPAddr) port := strconv.Itoa(hp.Port) if hp.IP.IsUnspecified() { var ip net.IP ifaces, _ := net.Interfaces() for _, i := range ifaces { addrs, _ := i.Addrs() for _, addr := range addrs { switch v := addr.(type) { case *net.IPNet: ip = v.IP hostPorts = append(hostPorts, net.JoinHostPort(ip.String(), port)) case *net.IPAddr: ip = v.IP hostPorts = append(hostPorts, net.JoinHostPort(ip.String(), port)) default: continue } } } } else { hostPorts = append(hostPorts, net.JoinHostPort(hp.IP.String(), port)) } return hostPorts }
go
func resolveHostPorts(addr net.Listener) []string { hostPorts := make([]string, 0) hp := addr.Addr().(*net.TCPAddr) port := strconv.Itoa(hp.Port) if hp.IP.IsUnspecified() { var ip net.IP ifaces, _ := net.Interfaces() for _, i := range ifaces { addrs, _ := i.Addrs() for _, addr := range addrs { switch v := addr.(type) { case *net.IPNet: ip = v.IP hostPorts = append(hostPorts, net.JoinHostPort(ip.String(), port)) case *net.IPAddr: ip = v.IP hostPorts = append(hostPorts, net.JoinHostPort(ip.String(), port)) default: continue } } } } else { hostPorts = append(hostPorts, net.JoinHostPort(hp.IP.String(), port)) } return hostPorts }
[ "func", "resolveHostPorts", "(", "addr", "net", ".", "Listener", ")", "[", "]", "string", "{", "hostPorts", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "hp", ":=", "addr", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", "\n", "port", ":=", "strconv", ".", "Itoa", "(", "hp", ".", "Port", ")", "\n", "if", "hp", ".", "IP", ".", "IsUnspecified", "(", ")", "{", "var", "ip", "net", ".", "IP", "\n", "ifaces", ",", "_", ":=", "net", ".", "Interfaces", "(", ")", "\n", "for", "_", ",", "i", ":=", "range", "ifaces", "{", "addrs", ",", "_", ":=", "i", ".", "Addrs", "(", ")", "\n", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "switch", "v", ":=", "addr", ".", "(", "type", ")", "{", "case", "*", "net", ".", "IPNet", ":", "ip", "=", "v", ".", "IP", "\n", "hostPorts", "=", "append", "(", "hostPorts", ",", "net", ".", "JoinHostPort", "(", "ip", ".", "String", "(", ")", ",", "port", ")", ")", "\n", "case", "*", "net", ".", "IPAddr", ":", "ip", "=", "v", ".", "IP", "\n", "hostPorts", "=", "append", "(", "hostPorts", ",", "net", ".", "JoinHostPort", "(", "ip", ".", "String", "(", ")", ",", "port", ")", ")", "\n", "default", ":", "continue", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "else", "{", "hostPorts", "=", "append", "(", "hostPorts", ",", "net", ".", "JoinHostPort", "(", "hp", ".", "IP", ".", "String", "(", ")", ",", "port", ")", ")", "\n", "}", "\n", "return", "hostPorts", "\n", "}" ]
// if the ip is not specified, attempt to resolve it
[ "if", "the", "ip", "is", "not", "specified", "attempt", "to", "resolve", "it" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L2008-L2034
164,113
nats-io/gnatsd
server/server.go
formatURL
func formatURL(protocol string, addr net.Listener) []string { hostports := resolveHostPorts(addr) for i, hp := range hostports { hostports[i] = fmt.Sprintf("%s://%s", protocol, hp) } return hostports }
go
func formatURL(protocol string, addr net.Listener) []string { hostports := resolveHostPorts(addr) for i, hp := range hostports { hostports[i] = fmt.Sprintf("%s://%s", protocol, hp) } return hostports }
[ "func", "formatURL", "(", "protocol", "string", ",", "addr", "net", ".", "Listener", ")", "[", "]", "string", "{", "hostports", ":=", "resolveHostPorts", "(", "addr", ")", "\n", "for", "i", ",", "hp", ":=", "range", "hostports", "{", "hostports", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "protocol", ",", "hp", ")", "\n", "}", "\n", "return", "hostports", "\n", "}" ]
// format the address of a net.Listener with a protocol
[ "format", "the", "address", "of", "a", "net", ".", "Listener", "with", "a", "protocol" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L2037-L2043
164,114
nats-io/gnatsd
server/server.go
PortsInfo
func (s *Server) PortsInfo(maxWait time.Duration) *Ports { if s.readyForListeners(maxWait) { opts := s.getOpts() s.mu.Lock() info := s.copyInfo() listener := s.listener httpListener := s.http clusterListener := s.routeListener profileListener := s.profiler s.mu.Unlock() ports := Ports{} if listener != nil { natsProto := "nats" if info.TLSRequired { natsProto = "tls" } ports.Nats = formatURL(natsProto, listener) } if httpListener != nil { monProto := "http" if opts.HTTPSPort != 0 { monProto = "https" } ports.Monitoring = formatURL(monProto, httpListener) } if clusterListener != nil { clusterProto := "nats" if opts.Cluster.TLSConfig != nil { clusterProto = "tls" } ports.Cluster = formatURL(clusterProto, clusterListener) } if profileListener != nil { ports.Profile = formatURL("http", profileListener) } return &ports } return nil }
go
func (s *Server) PortsInfo(maxWait time.Duration) *Ports { if s.readyForListeners(maxWait) { opts := s.getOpts() s.mu.Lock() info := s.copyInfo() listener := s.listener httpListener := s.http clusterListener := s.routeListener profileListener := s.profiler s.mu.Unlock() ports := Ports{} if listener != nil { natsProto := "nats" if info.TLSRequired { natsProto = "tls" } ports.Nats = formatURL(natsProto, listener) } if httpListener != nil { monProto := "http" if opts.HTTPSPort != 0 { monProto = "https" } ports.Monitoring = formatURL(monProto, httpListener) } if clusterListener != nil { clusterProto := "nats" if opts.Cluster.TLSConfig != nil { clusterProto = "tls" } ports.Cluster = formatURL(clusterProto, clusterListener) } if profileListener != nil { ports.Profile = formatURL("http", profileListener) } return &ports } return nil }
[ "func", "(", "s", "*", "Server", ")", "PortsInfo", "(", "maxWait", "time", ".", "Duration", ")", "*", "Ports", "{", "if", "s", ".", "readyForListeners", "(", "maxWait", ")", "{", "opts", ":=", "s", ".", "getOpts", "(", ")", "\n\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "info", ":=", "s", ".", "copyInfo", "(", ")", "\n", "listener", ":=", "s", ".", "listener", "\n", "httpListener", ":=", "s", ".", "http", "\n", "clusterListener", ":=", "s", ".", "routeListener", "\n", "profileListener", ":=", "s", ".", "profiler", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "ports", ":=", "Ports", "{", "}", "\n\n", "if", "listener", "!=", "nil", "{", "natsProto", ":=", "\"", "\"", "\n", "if", "info", ".", "TLSRequired", "{", "natsProto", "=", "\"", "\"", "\n", "}", "\n", "ports", ".", "Nats", "=", "formatURL", "(", "natsProto", ",", "listener", ")", "\n", "}", "\n\n", "if", "httpListener", "!=", "nil", "{", "monProto", ":=", "\"", "\"", "\n", "if", "opts", ".", "HTTPSPort", "!=", "0", "{", "monProto", "=", "\"", "\"", "\n", "}", "\n", "ports", ".", "Monitoring", "=", "formatURL", "(", "monProto", ",", "httpListener", ")", "\n", "}", "\n\n", "if", "clusterListener", "!=", "nil", "{", "clusterProto", ":=", "\"", "\"", "\n", "if", "opts", ".", "Cluster", ".", "TLSConfig", "!=", "nil", "{", "clusterProto", "=", "\"", "\"", "\n", "}", "\n", "ports", ".", "Cluster", "=", "formatURL", "(", "clusterProto", ",", "clusterListener", ")", "\n", "}", "\n\n", "if", "profileListener", "!=", "nil", "{", "ports", ".", "Profile", "=", "formatURL", "(", "\"", "\"", ",", "profileListener", ")", "\n", "}", "\n\n", "return", "&", "ports", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// PortsInfo attempts to resolve all the ports. If after maxWait the ports are not // resolved, it returns nil. Otherwise it returns a Ports struct // describing ports where the server can be contacted
[ "PortsInfo", "attempts", "to", "resolve", "all", "the", "ports", ".", "If", "after", "maxWait", "the", "ports", "are", "not", "resolved", "it", "returns", "nil", ".", "Otherwise", "it", "returns", "a", "Ports", "struct", "describing", "ports", "where", "the", "server", "can", "be", "contacted" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L2056-L2102
164,115
nats-io/gnatsd
server/server.go
portFile
func (s *Server) portFile(dirHint string) string { dirname := s.getOpts().PortsFileDir if dirHint != "" { dirname = dirHint } if dirname == _EMPTY_ { return _EMPTY_ } return filepath.Join(dirname, fmt.Sprintf("%s_%d.ports", filepath.Base(os.Args[0]), os.Getpid())) }
go
func (s *Server) portFile(dirHint string) string { dirname := s.getOpts().PortsFileDir if dirHint != "" { dirname = dirHint } if dirname == _EMPTY_ { return _EMPTY_ } return filepath.Join(dirname, fmt.Sprintf("%s_%d.ports", filepath.Base(os.Args[0]), os.Getpid())) }
[ "func", "(", "s", "*", "Server", ")", "portFile", "(", "dirHint", "string", ")", "string", "{", "dirname", ":=", "s", ".", "getOpts", "(", ")", ".", "PortsFileDir", "\n", "if", "dirHint", "!=", "\"", "\"", "{", "dirname", "=", "dirHint", "\n", "}", "\n", "if", "dirname", "==", "_EMPTY_", "{", "return", "_EMPTY_", "\n", "}", "\n", "return", "filepath", ".", "Join", "(", "dirname", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filepath", ".", "Base", "(", "os", ".", "Args", "[", "0", "]", ")", ",", "os", ".", "Getpid", "(", ")", ")", ")", "\n", "}" ]
// Returns the portsFile. If a non-empty dirHint is provided, the dirHint // path is used instead of the server option value
[ "Returns", "the", "portsFile", ".", "If", "a", "non", "-", "empty", "dirHint", "is", "provided", "the", "dirHint", "path", "is", "used", "instead", "of", "the", "server", "option", "value" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L2106-L2115
164,116
nats-io/gnatsd
server/server.go
deletePortsFile
func (s *Server) deletePortsFile(hintDir string) { portsFile := s.portFile(hintDir) if portsFile != "" { if err := os.Remove(portsFile); err != nil { s.Errorf("Error cleaning up ports file %s: %v", portsFile, err) } } }
go
func (s *Server) deletePortsFile(hintDir string) { portsFile := s.portFile(hintDir) if portsFile != "" { if err := os.Remove(portsFile); err != nil { s.Errorf("Error cleaning up ports file %s: %v", portsFile, err) } } }
[ "func", "(", "s", "*", "Server", ")", "deletePortsFile", "(", "hintDir", "string", ")", "{", "portsFile", ":=", "s", ".", "portFile", "(", "hintDir", ")", "\n", "if", "portsFile", "!=", "\"", "\"", "{", "if", "err", ":=", "os", ".", "Remove", "(", "portsFile", ")", ";", "err", "!=", "nil", "{", "s", ".", "Errorf", "(", "\"", "\"", ",", "portsFile", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Delete the ports file. If a non-empty dirHint is provided, the dirHint // path is used instead of the server option value
[ "Delete", "the", "ports", "file", ".", "If", "a", "non", "-", "empty", "dirHint", "is", "provided", "the", "dirHint", "path", "is", "used", "instead", "of", "the", "server", "option", "value" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L2119-L2126
164,117
nats-io/gnatsd
server/server.go
logPorts
func (s *Server) logPorts() { opts := s.getOpts() portsFile := s.portFile(opts.PortsFileDir) if portsFile != _EMPTY_ { go func() { info := s.PortsInfo(5 * time.Second) if info == nil { s.Errorf("Unable to resolve the ports in the specified time") return } data, err := json.Marshal(info) if err != nil { s.Errorf("Error marshaling ports file: %v", err) return } if err := ioutil.WriteFile(portsFile, data, 0666); err != nil { s.Errorf("Error writing ports file (%s): %v", portsFile, err) return } }() } }
go
func (s *Server) logPorts() { opts := s.getOpts() portsFile := s.portFile(opts.PortsFileDir) if portsFile != _EMPTY_ { go func() { info := s.PortsInfo(5 * time.Second) if info == nil { s.Errorf("Unable to resolve the ports in the specified time") return } data, err := json.Marshal(info) if err != nil { s.Errorf("Error marshaling ports file: %v", err) return } if err := ioutil.WriteFile(portsFile, data, 0666); err != nil { s.Errorf("Error writing ports file (%s): %v", portsFile, err) return } }() } }
[ "func", "(", "s", "*", "Server", ")", "logPorts", "(", ")", "{", "opts", ":=", "s", ".", "getOpts", "(", ")", "\n", "portsFile", ":=", "s", ".", "portFile", "(", "opts", ".", "PortsFileDir", ")", "\n", "if", "portsFile", "!=", "_EMPTY_", "{", "go", "func", "(", ")", "{", "info", ":=", "s", ".", "PortsInfo", "(", "5", "*", "time", ".", "Second", ")", "\n", "if", "info", "==", "nil", "{", "s", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "info", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "portsFile", ",", "data", ",", "0666", ")", ";", "err", "!=", "nil", "{", "s", ".", "Errorf", "(", "\"", "\"", ",", "portsFile", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "}", "(", ")", "\n", "}", "\n", "}" ]
// Writes a file with a serialized Ports to the specified ports_file_dir. // The name of the file is `exename_pid.ports`, typically gnatsd_pid.ports. // if ports file is not set, this function has no effect
[ "Writes", "a", "file", "with", "a", "serialized", "Ports", "to", "the", "specified", "ports_file_dir", ".", "The", "name", "of", "the", "file", "is", "exename_pid", ".", "ports", "typically", "gnatsd_pid", ".", "ports", ".", "if", "ports", "file", "is", "not", "set", "this", "function", "has", "no", "effect" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L2131-L2153
164,118
nats-io/gnatsd
server/server.go
readyForListeners
func (s *Server) readyForListeners(dur time.Duration) bool { end := time.Now().Add(dur) for time.Now().Before(end) { s.mu.Lock() listeners := s.serviceListeners() s.mu.Unlock() if len(listeners) == 0 { return false } ok := true for _, l := range listeners { if l == nil { ok = false break } } if ok { return true } select { case <-s.quitCh: return false case <-time.After(25 * time.Millisecond): // continue - unable to select from quit - we are still running } } return false }
go
func (s *Server) readyForListeners(dur time.Duration) bool { end := time.Now().Add(dur) for time.Now().Before(end) { s.mu.Lock() listeners := s.serviceListeners() s.mu.Unlock() if len(listeners) == 0 { return false } ok := true for _, l := range listeners { if l == nil { ok = false break } } if ok { return true } select { case <-s.quitCh: return false case <-time.After(25 * time.Millisecond): // continue - unable to select from quit - we are still running } } return false }
[ "func", "(", "s", "*", "Server", ")", "readyForListeners", "(", "dur", "time", ".", "Duration", ")", "bool", "{", "end", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "dur", ")", "\n", "for", "time", ".", "Now", "(", ")", ".", "Before", "(", "end", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "listeners", ":=", "s", ".", "serviceListeners", "(", ")", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "len", "(", "listeners", ")", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "ok", ":=", "true", "\n", "for", "_", ",", "l", ":=", "range", "listeners", "{", "if", "l", "==", "nil", "{", "ok", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "ok", "{", "return", "true", "\n", "}", "\n", "select", "{", "case", "<-", "s", ".", "quitCh", ":", "return", "false", "\n", "case", "<-", "time", ".", "After", "(", "25", "*", "time", ".", "Millisecond", ")", ":", "// continue - unable to select from quit - we are still running", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// waits until a calculated list of listeners is resolved or a timeout
[ "waits", "until", "a", "calculated", "list", "of", "listeners", "is", "resolved", "or", "a", "timeout" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L2156-L2184
164,119
nats-io/gnatsd
server/server.go
serviceListeners
func (s *Server) serviceListeners() []net.Listener { listeners := make([]net.Listener, 0) opts := s.getOpts() listeners = append(listeners, s.listener) if opts.Cluster.Port != 0 { listeners = append(listeners, s.routeListener) } if opts.HTTPPort != 0 || opts.HTTPSPort != 0 { listeners = append(listeners, s.http) } if opts.ProfPort != 0 { listeners = append(listeners, s.profiler) } return listeners }
go
func (s *Server) serviceListeners() []net.Listener { listeners := make([]net.Listener, 0) opts := s.getOpts() listeners = append(listeners, s.listener) if opts.Cluster.Port != 0 { listeners = append(listeners, s.routeListener) } if opts.HTTPPort != 0 || opts.HTTPSPort != 0 { listeners = append(listeners, s.http) } if opts.ProfPort != 0 { listeners = append(listeners, s.profiler) } return listeners }
[ "func", "(", "s", "*", "Server", ")", "serviceListeners", "(", ")", "[", "]", "net", ".", "Listener", "{", "listeners", ":=", "make", "(", "[", "]", "net", ".", "Listener", ",", "0", ")", "\n", "opts", ":=", "s", ".", "getOpts", "(", ")", "\n", "listeners", "=", "append", "(", "listeners", ",", "s", ".", "listener", ")", "\n", "if", "opts", ".", "Cluster", ".", "Port", "!=", "0", "{", "listeners", "=", "append", "(", "listeners", ",", "s", ".", "routeListener", ")", "\n", "}", "\n", "if", "opts", ".", "HTTPPort", "!=", "0", "||", "opts", ".", "HTTPSPort", "!=", "0", "{", "listeners", "=", "append", "(", "listeners", ",", "s", ".", "http", ")", "\n", "}", "\n", "if", "opts", ".", "ProfPort", "!=", "0", "{", "listeners", "=", "append", "(", "listeners", ",", "s", ".", "profiler", ")", "\n", "}", "\n", "return", "listeners", "\n", "}" ]
// returns a list of listeners that are intended for the process // if the entry is nil, the interface is yet to be resolved
[ "returns", "a", "list", "of", "listeners", "that", "are", "intended", "for", "the", "process", "if", "the", "entry", "is", "nil", "the", "interface", "is", "yet", "to", "be", "resolved" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L2188-L2202
164,120
nats-io/gnatsd
server/server.go
isLameDuckMode
func (s *Server) isLameDuckMode() bool { s.mu.Lock() defer s.mu.Unlock() return s.ldm }
go
func (s *Server) isLameDuckMode() bool { s.mu.Lock() defer s.mu.Unlock() return s.ldm }
[ "func", "(", "s", "*", "Server", ")", "isLameDuckMode", "(", ")", "bool", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "ldm", "\n", "}" ]
// Returns true if in lame duck mode.
[ "Returns", "true", "if", "in", "lame", "duck", "mode", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L2205-L2209
164,121
nats-io/gnatsd
server/server.go
lameDuckMode
func (s *Server) lameDuckMode() { s.mu.Lock() // Check if there is actually anything to do if s.shutdown || s.ldm || s.listener == nil { s.mu.Unlock() return } s.Noticef("Entering lame duck mode, stop accepting new clients") s.ldm = true s.ldmCh = make(chan bool, 1) s.listener.Close() s.listener = nil s.mu.Unlock() // Wait for accept loop to be done to make sure that no new // client can connect <-s.ldmCh s.mu.Lock() // Need to recheck few things if s.shutdown || len(s.clients) == 0 { s.mu.Unlock() // If there is no client, we need to call Shutdown() to complete // the LDMode. If server has been shutdown while lock was released, // calling Shutdown() should be no-op. s.Shutdown() return } dur := int64(s.getOpts().LameDuckDuration) dur -= atomic.LoadInt64(&lameDuckModeInitialDelay) if dur <= 0 { dur = int64(time.Second) } numClients := int64(len(s.clients)) batch := 1 // Sleep interval between each client connection close. si := dur / numClients if si < 1 { // Should not happen (except in test with very small LD duration), but // if there are too many clients, batch the number of close and // use a tiny sleep interval that will result in yield likely. si = 1 batch = int(numClients / dur) } else if si > int64(time.Second) { // Conversely, there is no need to sleep too long between clients // and spread say 10 clients for the 2min duration. Sleeping no // more than 1sec. si = int64(time.Second) } // Now capture all clients clients := make([]*client, 0, len(s.clients)) for _, client := range s.clients { clients = append(clients, client) } s.mu.Unlock() t := time.NewTimer(time.Duration(atomic.LoadInt64(&lameDuckModeInitialDelay))) // Delay start of closing of client connections in case // we have several servers that we want to signal to enter LD mode // and not have their client reconnect to each other. select { case <-t.C: s.Noticef("Closing existing clients") case <-s.quitCh: return } for i, client := range clients { client.closeConnection(ServerShutdown) if i == len(clients)-1 { break } if batch == 1 || i%batch == 0 { // We pick a random interval which will be at least si/2 v := rand.Int63n(si) if v < si/2 { v = si / 2 } t.Reset(time.Duration(v)) // Sleep for given interval or bail out if kicked by Shutdown(). select { case <-t.C: case <-s.quitCh: t.Stop() return } } } s.Shutdown() }
go
func (s *Server) lameDuckMode() { s.mu.Lock() // Check if there is actually anything to do if s.shutdown || s.ldm || s.listener == nil { s.mu.Unlock() return } s.Noticef("Entering lame duck mode, stop accepting new clients") s.ldm = true s.ldmCh = make(chan bool, 1) s.listener.Close() s.listener = nil s.mu.Unlock() // Wait for accept loop to be done to make sure that no new // client can connect <-s.ldmCh s.mu.Lock() // Need to recheck few things if s.shutdown || len(s.clients) == 0 { s.mu.Unlock() // If there is no client, we need to call Shutdown() to complete // the LDMode. If server has been shutdown while lock was released, // calling Shutdown() should be no-op. s.Shutdown() return } dur := int64(s.getOpts().LameDuckDuration) dur -= atomic.LoadInt64(&lameDuckModeInitialDelay) if dur <= 0 { dur = int64(time.Second) } numClients := int64(len(s.clients)) batch := 1 // Sleep interval between each client connection close. si := dur / numClients if si < 1 { // Should not happen (except in test with very small LD duration), but // if there are too many clients, batch the number of close and // use a tiny sleep interval that will result in yield likely. si = 1 batch = int(numClients / dur) } else if si > int64(time.Second) { // Conversely, there is no need to sleep too long between clients // and spread say 10 clients for the 2min duration. Sleeping no // more than 1sec. si = int64(time.Second) } // Now capture all clients clients := make([]*client, 0, len(s.clients)) for _, client := range s.clients { clients = append(clients, client) } s.mu.Unlock() t := time.NewTimer(time.Duration(atomic.LoadInt64(&lameDuckModeInitialDelay))) // Delay start of closing of client connections in case // we have several servers that we want to signal to enter LD mode // and not have their client reconnect to each other. select { case <-t.C: s.Noticef("Closing existing clients") case <-s.quitCh: return } for i, client := range clients { client.closeConnection(ServerShutdown) if i == len(clients)-1 { break } if batch == 1 || i%batch == 0 { // We pick a random interval which will be at least si/2 v := rand.Int63n(si) if v < si/2 { v = si / 2 } t.Reset(time.Duration(v)) // Sleep for given interval or bail out if kicked by Shutdown(). select { case <-t.C: case <-s.quitCh: t.Stop() return } } } s.Shutdown() }
[ "func", "(", "s", "*", "Server", ")", "lameDuckMode", "(", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "// Check if there is actually anything to do", "if", "s", ".", "shutdown", "||", "s", ".", "ldm", "||", "s", ".", "listener", "==", "nil", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "s", ".", "Noticef", "(", "\"", "\"", ")", "\n", "s", ".", "ldm", "=", "true", "\n", "s", ".", "ldmCh", "=", "make", "(", "chan", "bool", ",", "1", ")", "\n", "s", ".", "listener", ".", "Close", "(", ")", "\n", "s", ".", "listener", "=", "nil", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Wait for accept loop to be done to make sure that no new", "// client can connect", "<-", "s", ".", "ldmCh", "\n\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "// Need to recheck few things", "if", "s", ".", "shutdown", "||", "len", "(", "s", ".", "clients", ")", "==", "0", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "// If there is no client, we need to call Shutdown() to complete", "// the LDMode. If server has been shutdown while lock was released,", "// calling Shutdown() should be no-op.", "s", ".", "Shutdown", "(", ")", "\n", "return", "\n", "}", "\n", "dur", ":=", "int64", "(", "s", ".", "getOpts", "(", ")", ".", "LameDuckDuration", ")", "\n", "dur", "-=", "atomic", ".", "LoadInt64", "(", "&", "lameDuckModeInitialDelay", ")", "\n", "if", "dur", "<=", "0", "{", "dur", "=", "int64", "(", "time", ".", "Second", ")", "\n", "}", "\n", "numClients", ":=", "int64", "(", "len", "(", "s", ".", "clients", ")", ")", "\n", "batch", ":=", "1", "\n", "// Sleep interval between each client connection close.", "si", ":=", "dur", "/", "numClients", "\n", "if", "si", "<", "1", "{", "// Should not happen (except in test with very small LD duration), but", "// if there are too many clients, batch the number of close and", "// use a tiny sleep interval that will result in yield likely.", "si", "=", "1", "\n", "batch", "=", "int", "(", "numClients", "/", "dur", ")", "\n", "}", "else", "if", "si", ">", "int64", "(", "time", ".", "Second", ")", "{", "// Conversely, there is no need to sleep too long between clients", "// and spread say 10 clients for the 2min duration. Sleeping no", "// more than 1sec.", "si", "=", "int64", "(", "time", ".", "Second", ")", "\n", "}", "\n\n", "// Now capture all clients", "clients", ":=", "make", "(", "[", "]", "*", "client", ",", "0", ",", "len", "(", "s", ".", "clients", ")", ")", "\n", "for", "_", ",", "client", ":=", "range", "s", ".", "clients", "{", "clients", "=", "append", "(", "clients", ",", "client", ")", "\n", "}", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "t", ":=", "time", ".", "NewTimer", "(", "time", ".", "Duration", "(", "atomic", ".", "LoadInt64", "(", "&", "lameDuckModeInitialDelay", ")", ")", ")", "\n", "// Delay start of closing of client connections in case", "// we have several servers that we want to signal to enter LD mode", "// and not have their client reconnect to each other.", "select", "{", "case", "<-", "t", ".", "C", ":", "s", ".", "Noticef", "(", "\"", "\"", ")", "\n", "case", "<-", "s", ".", "quitCh", ":", "return", "\n", "}", "\n", "for", "i", ",", "client", ":=", "range", "clients", "{", "client", ".", "closeConnection", "(", "ServerShutdown", ")", "\n", "if", "i", "==", "len", "(", "clients", ")", "-", "1", "{", "break", "\n", "}", "\n", "if", "batch", "==", "1", "||", "i", "%", "batch", "==", "0", "{", "// We pick a random interval which will be at least si/2", "v", ":=", "rand", ".", "Int63n", "(", "si", ")", "\n", "if", "v", "<", "si", "/", "2", "{", "v", "=", "si", "/", "2", "\n", "}", "\n", "t", ".", "Reset", "(", "time", ".", "Duration", "(", "v", ")", ")", "\n", "// Sleep for given interval or bail out if kicked by Shutdown().", "select", "{", "case", "<-", "t", ".", "C", ":", "case", "<-", "s", ".", "quitCh", ":", "t", ".", "Stop", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "s", ".", "Shutdown", "(", ")", "\n", "}" ]
// This function will close the client listener then close the clients // at some interval to avoid a reconnecting storm.
[ "This", "function", "will", "close", "the", "client", "listener", "then", "close", "the", "clients", "at", "some", "interval", "to", "avoid", "a", "reconnecting", "storm", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L2213-L2302
164,122
nats-io/gnatsd
server/pse/pse_windows.go
pdhGetFormattedCounterArrayDouble
func pdhGetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER, lpdwBufferSize *uint32, lpdwBufferCount *uint32, itemBuffer *PDH_FMT_COUNTERVALUE_ITEM_DOUBLE) uint32 { ret, _, _ := winPdhGetFormattedCounterArray.Call( uintptr(hCounter), uintptr(PDH_FMT_DOUBLE), uintptr(unsafe.Pointer(lpdwBufferSize)), uintptr(unsafe.Pointer(lpdwBufferCount)), uintptr(unsafe.Pointer(itemBuffer))) return uint32(ret) }
go
func pdhGetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER, lpdwBufferSize *uint32, lpdwBufferCount *uint32, itemBuffer *PDH_FMT_COUNTERVALUE_ITEM_DOUBLE) uint32 { ret, _, _ := winPdhGetFormattedCounterArray.Call( uintptr(hCounter), uintptr(PDH_FMT_DOUBLE), uintptr(unsafe.Pointer(lpdwBufferSize)), uintptr(unsafe.Pointer(lpdwBufferCount)), uintptr(unsafe.Pointer(itemBuffer))) return uint32(ret) }
[ "func", "pdhGetFormattedCounterArrayDouble", "(", "hCounter", "PDH_HCOUNTER", ",", "lpdwBufferSize", "*", "uint32", ",", "lpdwBufferCount", "*", "uint32", ",", "itemBuffer", "*", "PDH_FMT_COUNTERVALUE_ITEM_DOUBLE", ")", "uint32", "{", "ret", ",", "_", ",", "_", ":=", "winPdhGetFormattedCounterArray", ".", "Call", "(", "uintptr", "(", "hCounter", ")", ",", "uintptr", "(", "PDH_FMT_DOUBLE", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "lpdwBufferSize", ")", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "lpdwBufferCount", ")", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "itemBuffer", ")", ")", ")", "\n\n", "return", "uint32", "(", "ret", ")", "\n", "}" ]
// pdhGetFormattedCounterArrayDouble returns the value of return code // rather than error, to easily check return codes
[ "pdhGetFormattedCounterArrayDouble", "returns", "the", "value", "of", "return", "code", "rather", "than", "error", "to", "easily", "check", "return", "codes" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/pse/pse_windows.go#L118-L127
164,123
nats-io/gnatsd
server/pse/pse_windows.go
getProcessImageName
func getProcessImageName() (name string) { name = filepath.Base(os.Args[0]) name = strings.TrimRight(name, ".exe") return }
go
func getProcessImageName() (name string) { name = filepath.Base(os.Args[0]) name = strings.TrimRight(name, ".exe") return }
[ "func", "getProcessImageName", "(", ")", "(", "name", "string", ")", "{", "name", "=", "filepath", ".", "Base", "(", "os", ".", "Args", "[", "0", "]", ")", "\n", "name", "=", "strings", ".", "TrimRight", "(", "name", ",", "\"", "\"", ")", "\n", "return", "\n", "}" ]
// getProcessImageName returns the name of the process image, as expected by // the performance counter API.
[ "getProcessImageName", "returns", "the", "name", "of", "the", "process", "image", "as", "expected", "by", "the", "performance", "counter", "API", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/pse/pse_windows.go#L161-L165
164,124
nats-io/gnatsd
server/pse/pse_windows.go
initCounters
func initCounters() (err error) { processPid = os.Getpid() // require an addressible nil pointer var source uint16 if err := pdhOpenQuery(&source, 0, &pcHandle); err != nil { return err } // setup the performance counters, search for all server instances name := fmt.Sprintf("%s*", getProcessImageName()) pidQuery := fmt.Sprintf("\\Process(%s)\\ID Process", name) cpuQuery := fmt.Sprintf("\\Process(%s)\\%% Processor Time", name) rssQuery := fmt.Sprintf("\\Process(%s)\\Working Set - Private", name) vssQuery := fmt.Sprintf("\\Process(%s)\\Virtual Bytes", name) if err = pdhAddCounter(pcHandle, pidQuery, 0, &pidCounter); err != nil { return err } if err = pdhAddCounter(pcHandle, cpuQuery, 0, &cpuCounter); err != nil { return err } if err = pdhAddCounter(pcHandle, rssQuery, 0, &rssCounter); err != nil { return err } if err = pdhAddCounter(pcHandle, vssQuery, 0, &vssCounter); err != nil { return err } // prime the counters by collecting once, and sleep to get somewhat // useful information the first request. Counters for the CPU require // at least two collect calls. if err = pdhCollectQueryData(pcHandle); err != nil { return err } time.Sleep(50) return nil }
go
func initCounters() (err error) { processPid = os.Getpid() // require an addressible nil pointer var source uint16 if err := pdhOpenQuery(&source, 0, &pcHandle); err != nil { return err } // setup the performance counters, search for all server instances name := fmt.Sprintf("%s*", getProcessImageName()) pidQuery := fmt.Sprintf("\\Process(%s)\\ID Process", name) cpuQuery := fmt.Sprintf("\\Process(%s)\\%% Processor Time", name) rssQuery := fmt.Sprintf("\\Process(%s)\\Working Set - Private", name) vssQuery := fmt.Sprintf("\\Process(%s)\\Virtual Bytes", name) if err = pdhAddCounter(pcHandle, pidQuery, 0, &pidCounter); err != nil { return err } if err = pdhAddCounter(pcHandle, cpuQuery, 0, &cpuCounter); err != nil { return err } if err = pdhAddCounter(pcHandle, rssQuery, 0, &rssCounter); err != nil { return err } if err = pdhAddCounter(pcHandle, vssQuery, 0, &vssCounter); err != nil { return err } // prime the counters by collecting once, and sleep to get somewhat // useful information the first request. Counters for the CPU require // at least two collect calls. if err = pdhCollectQueryData(pcHandle); err != nil { return err } time.Sleep(50) return nil }
[ "func", "initCounters", "(", ")", "(", "err", "error", ")", "{", "processPid", "=", "os", ".", "Getpid", "(", ")", "\n", "// require an addressible nil pointer", "var", "source", "uint16", "\n", "if", "err", ":=", "pdhOpenQuery", "(", "&", "source", ",", "0", ",", "&", "pcHandle", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// setup the performance counters, search for all server instances", "name", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "getProcessImageName", "(", ")", ")", "\n", "pidQuery", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\\\", "\\\\", "\"", ",", "name", ")", "\n", "cpuQuery", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\\\", "\\\\", "\"", ",", "name", ")", "\n", "rssQuery", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\\\", "\\\\", "\"", ",", "name", ")", "\n", "vssQuery", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\\\", "\\\\", "\"", ",", "name", ")", "\n\n", "if", "err", "=", "pdhAddCounter", "(", "pcHandle", ",", "pidQuery", ",", "0", ",", "&", "pidCounter", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "pdhAddCounter", "(", "pcHandle", ",", "cpuQuery", ",", "0", ",", "&", "cpuCounter", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "pdhAddCounter", "(", "pcHandle", ",", "rssQuery", ",", "0", ",", "&", "rssCounter", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "pdhAddCounter", "(", "pcHandle", ",", "vssQuery", ",", "0", ",", "&", "vssCounter", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// prime the counters by collecting once, and sleep to get somewhat", "// useful information the first request. Counters for the CPU require", "// at least two collect calls.", "if", "err", "=", "pdhCollectQueryData", "(", "pcHandle", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "time", ".", "Sleep", "(", "50", ")", "\n\n", "return", "nil", "\n", "}" ]
// initialize our counters
[ "initialize", "our", "counters" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/pse/pse_windows.go#L168-L206
164,125
nats-io/gnatsd
server/pse/pse_windows.go
ProcUsage
func ProcUsage(pcpu *float64, rss, vss *int64) error { var err error // For simplicity, protect the entire call. // Most simultaneous requests will immediately return // with cached values. pcQueryLock.Lock() defer pcQueryLock.Unlock() // First time through, initialize counters. if initialSample { if err = initCounters(); err != nil { return err } initialSample = false } else if time.Since(lastSampleTime) < (2 * time.Second) { // only refresh every two seconds as to minimize impact // on the server. *pcpu = prevCPU *rss = prevRss *vss = prevVss return nil } // always save the sample time, even on errors. defer func() { lastSampleTime = time.Now() }() // refresh the performance counter data if err = pdhCollectQueryData(pcHandle); err != nil { return err } // retrieve the data var pidAry, cpuAry, rssAry, vssAry []float64 if pidAry, err = getCounterArrayData(pidCounter); err != nil { return err } if cpuAry, err = getCounterArrayData(cpuCounter); err != nil { return err } if rssAry, err = getCounterArrayData(rssCounter); err != nil { return err } if vssAry, err = getCounterArrayData(vssCounter); err != nil { return err } // find the index of the entry for this process idx := int(-1) for i := range pidAry { if int(pidAry[i]) == processPid { idx = i break } } // no pid found... if idx < 0 { return fmt.Errorf("could not find pid in performance counter results") } // assign values from the performance counters *pcpu = cpuAry[idx] *rss = int64(rssAry[idx]) *vss = int64(vssAry[idx]) // save off cache values prevCPU = *pcpu prevRss = *rss prevVss = *vss return nil }
go
func ProcUsage(pcpu *float64, rss, vss *int64) error { var err error // For simplicity, protect the entire call. // Most simultaneous requests will immediately return // with cached values. pcQueryLock.Lock() defer pcQueryLock.Unlock() // First time through, initialize counters. if initialSample { if err = initCounters(); err != nil { return err } initialSample = false } else if time.Since(lastSampleTime) < (2 * time.Second) { // only refresh every two seconds as to minimize impact // on the server. *pcpu = prevCPU *rss = prevRss *vss = prevVss return nil } // always save the sample time, even on errors. defer func() { lastSampleTime = time.Now() }() // refresh the performance counter data if err = pdhCollectQueryData(pcHandle); err != nil { return err } // retrieve the data var pidAry, cpuAry, rssAry, vssAry []float64 if pidAry, err = getCounterArrayData(pidCounter); err != nil { return err } if cpuAry, err = getCounterArrayData(cpuCounter); err != nil { return err } if rssAry, err = getCounterArrayData(rssCounter); err != nil { return err } if vssAry, err = getCounterArrayData(vssCounter); err != nil { return err } // find the index of the entry for this process idx := int(-1) for i := range pidAry { if int(pidAry[i]) == processPid { idx = i break } } // no pid found... if idx < 0 { return fmt.Errorf("could not find pid in performance counter results") } // assign values from the performance counters *pcpu = cpuAry[idx] *rss = int64(rssAry[idx]) *vss = int64(vssAry[idx]) // save off cache values prevCPU = *pcpu prevRss = *rss prevVss = *vss return nil }
[ "func", "ProcUsage", "(", "pcpu", "*", "float64", ",", "rss", ",", "vss", "*", "int64", ")", "error", "{", "var", "err", "error", "\n\n", "// For simplicity, protect the entire call.", "// Most simultaneous requests will immediately return", "// with cached values.", "pcQueryLock", ".", "Lock", "(", ")", "\n", "defer", "pcQueryLock", ".", "Unlock", "(", ")", "\n\n", "// First time through, initialize counters.", "if", "initialSample", "{", "if", "err", "=", "initCounters", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "initialSample", "=", "false", "\n", "}", "else", "if", "time", ".", "Since", "(", "lastSampleTime", ")", "<", "(", "2", "*", "time", ".", "Second", ")", "{", "// only refresh every two seconds as to minimize impact", "// on the server.", "*", "pcpu", "=", "prevCPU", "\n", "*", "rss", "=", "prevRss", "\n", "*", "vss", "=", "prevVss", "\n", "return", "nil", "\n", "}", "\n\n", "// always save the sample time, even on errors.", "defer", "func", "(", ")", "{", "lastSampleTime", "=", "time", ".", "Now", "(", ")", "\n", "}", "(", ")", "\n\n", "// refresh the performance counter data", "if", "err", "=", "pdhCollectQueryData", "(", "pcHandle", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// retrieve the data", "var", "pidAry", ",", "cpuAry", ",", "rssAry", ",", "vssAry", "[", "]", "float64", "\n", "if", "pidAry", ",", "err", "=", "getCounterArrayData", "(", "pidCounter", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "cpuAry", ",", "err", "=", "getCounterArrayData", "(", "cpuCounter", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "rssAry", ",", "err", "=", "getCounterArrayData", "(", "rssCounter", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "vssAry", ",", "err", "=", "getCounterArrayData", "(", "vssCounter", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// find the index of the entry for this process", "idx", ":=", "int", "(", "-", "1", ")", "\n", "for", "i", ":=", "range", "pidAry", "{", "if", "int", "(", "pidAry", "[", "i", "]", ")", "==", "processPid", "{", "idx", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "// no pid found...", "if", "idx", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "// assign values from the performance counters", "*", "pcpu", "=", "cpuAry", "[", "idx", "]", "\n", "*", "rss", "=", "int64", "(", "rssAry", "[", "idx", "]", ")", "\n", "*", "vss", "=", "int64", "(", "vssAry", "[", "idx", "]", ")", "\n\n", "// save off cache values", "prevCPU", "=", "*", "pcpu", "\n", "prevRss", "=", "*", "rss", "\n", "prevVss", "=", "*", "vss", "\n\n", "return", "nil", "\n", "}" ]
// ProcUsage returns process CPU and memory statistics
[ "ProcUsage", "returns", "process", "CPU", "and", "memory", "statistics" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/pse/pse_windows.go#L209-L280
164,126
nats-io/gnatsd
server/nkey.go
NonceRequired
func (s *Server) NonceRequired() bool { s.mu.Lock() defer s.mu.Unlock() return s.nonceRequired() }
go
func (s *Server) NonceRequired() bool { s.mu.Lock() defer s.mu.Unlock() return s.nonceRequired() }
[ "func", "(", "s", "*", "Server", ")", "NonceRequired", "(", ")", "bool", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "s", ".", "nonceRequired", "(", ")", "\n", "}" ]
// NonceRequired tells us if we should send a nonce.
[ "NonceRequired", "tells", "us", "if", "we", "should", "send", "a", "nonce", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/nkey.go#L27-L31
164,127
nats-io/gnatsd
server/nkey.go
nonceRequired
func (s *Server) nonceRequired() bool { return len(s.nkeys) > 0 || len(s.trustedKeys) > 0 }
go
func (s *Server) nonceRequired() bool { return len(s.nkeys) > 0 || len(s.trustedKeys) > 0 }
[ "func", "(", "s", "*", "Server", ")", "nonceRequired", "(", ")", "bool", "{", "return", "len", "(", "s", ".", "nkeys", ")", ">", "0", "||", "len", "(", "s", ".", "trustedKeys", ")", ">", "0", "\n", "}" ]
// nonceRequired tells us if we should send a nonce. // Lock should be held on entry.
[ "nonceRequired", "tells", "us", "if", "we", "should", "send", "a", "nonce", ".", "Lock", "should", "be", "held", "on", "entry", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/nkey.go#L35-L37
164,128
nats-io/gnatsd
server/nkey.go
generateNonce
func (s *Server) generateNonce(n []byte) { var raw [nonceRawLen]byte data := raw[:] s.prand.Read(data) base64.RawURLEncoding.Encode(n, data) }
go
func (s *Server) generateNonce(n []byte) { var raw [nonceRawLen]byte data := raw[:] s.prand.Read(data) base64.RawURLEncoding.Encode(n, data) }
[ "func", "(", "s", "*", "Server", ")", "generateNonce", "(", "n", "[", "]", "byte", ")", "{", "var", "raw", "[", "nonceRawLen", "]", "byte", "\n", "data", ":=", "raw", "[", ":", "]", "\n", "s", ".", "prand", ".", "Read", "(", "data", ")", "\n", "base64", ".", "RawURLEncoding", ".", "Encode", "(", "n", ",", "data", ")", "\n", "}" ]
// Generate a nonce for INFO challenge. // Assumes server lock is held
[ "Generate", "a", "nonce", "for", "INFO", "challenge", ".", "Assumes", "server", "lock", "is", "held" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/nkey.go#L41-L46
164,129
nats-io/gnatsd
server/client.go
setIfNotSet
func (cf *clientFlag) setIfNotSet(c clientFlag) bool { if *cf&c == 0 { *cf |= c return true } return false }
go
func (cf *clientFlag) setIfNotSet(c clientFlag) bool { if *cf&c == 0 { *cf |= c return true } return false }
[ "func", "(", "cf", "*", "clientFlag", ")", "setIfNotSet", "(", "c", "clientFlag", ")", "bool", "{", "if", "*", "cf", "&", "c", "==", "0", "{", "*", "cf", "|=", "c", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// setIfNotSet will set the flag `c` only if that flag was not already // set and return true to indicate that the flag has been set. Returns // false otherwise.
[ "setIfNotSet", "will", "set", "the", "flag", "c", "only", "if", "that", "flag", "was", "not", "already", "set", "and", "return", "true", "to", "indicate", "that", "the", "flag", "has", "been", "set", ".", "Returns", "false", "otherwise", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L107-L113
164,130
nats-io/gnatsd
server/client.go
GetTLSConnectionState
func (c *client) GetTLSConnectionState() *tls.ConnectionState { tc, ok := c.nc.(*tls.Conn) if !ok { return nil } state := tc.ConnectionState() return &state }
go
func (c *client) GetTLSConnectionState() *tls.ConnectionState { tc, ok := c.nc.(*tls.Conn) if !ok { return nil } state := tc.ConnectionState() return &state }
[ "func", "(", "c", "*", "client", ")", "GetTLSConnectionState", "(", ")", "*", "tls", ".", "ConnectionState", "{", "tc", ",", "ok", ":=", "c", ".", "nc", ".", "(", "*", "tls", ".", "Conn", ")", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "state", ":=", "tc", ".", "ConnectionState", "(", ")", "\n", "return", "&", "state", "\n", "}" ]
// GetTLSConnectionState returns the TLS ConnectionState if TLS is enabled, nil // otherwise. Implements the ClientAuth interface.
[ "GetTLSConnectionState", "returns", "the", "TLS", "ConnectionState", "if", "TLS", "is", "enabled", "nil", "otherwise", ".", "Implements", "the", "ClientAuth", "interface", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L306-L313
164,131
nats-io/gnatsd
server/client.go
RemoteAddress
func (c *client) RemoteAddress() net.Addr { c.mu.Lock() defer c.mu.Unlock() if c.nc == nil { return nil } return c.nc.RemoteAddr() }
go
func (c *client) RemoteAddress() net.Addr { c.mu.Lock() defer c.mu.Unlock() if c.nc == nil { return nil } return c.nc.RemoteAddr() }
[ "func", "(", "c", "*", "client", ")", "RemoteAddress", "(", ")", "net", ".", "Addr", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "c", ".", "nc", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "c", ".", "nc", ".", "RemoteAddr", "(", ")", "\n", "}" ]
// RemoteAddress expose the Address of the client connection, // nil when not connected or unknown
[ "RemoteAddress", "expose", "the", "Address", "of", "the", "client", "connection", "nil", "when", "not", "connected", "or", "unknown" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L415-L424
164,132
nats-io/gnatsd
server/client.go
reportErrRegisterAccount
func (c *client) reportErrRegisterAccount(acc *Account, err error) { if err == ErrTooManyAccountConnections { c.maxAccountConnExceeded() return } c.Errorf("Problem registering with account [%s]", acc.Name) c.sendErr("Failed Account Registration") }
go
func (c *client) reportErrRegisterAccount(acc *Account, err error) { if err == ErrTooManyAccountConnections { c.maxAccountConnExceeded() return } c.Errorf("Problem registering with account [%s]", acc.Name) c.sendErr("Failed Account Registration") }
[ "func", "(", "c", "*", "client", ")", "reportErrRegisterAccount", "(", "acc", "*", "Account", ",", "err", "error", ")", "{", "if", "err", "==", "ErrTooManyAccountConnections", "{", "c", ".", "maxAccountConnExceeded", "(", ")", "\n", "return", "\n", "}", "\n", "c", ".", "Errorf", "(", "\"", "\"", ",", "acc", ".", "Name", ")", "\n", "c", ".", "sendErr", "(", "\"", "\"", ")", "\n", "}" ]
// Helper function to report errors.
[ "Helper", "function", "to", "report", "errors", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L427-L434
164,133
nats-io/gnatsd
server/client.go
registerWithAccount
func (c *client) registerWithAccount(acc *Account) error { if acc == nil || acc.sl == nil { return ErrBadAccount } // If we were previously registered, usually to $G, do accounting here to remove. if c.acc != nil { if prev := c.acc.removeClient(c); prev == 1 && c.srv != nil { c.srv.decActiveAccounts() } } c.mu.Lock() kind := c.kind srv := c.srv c.acc = acc c.applyAccountLimits() c.mu.Unlock() // Check if we have a max connections violation if kind == CLIENT && acc.MaxTotalConnectionsReached() { return ErrTooManyAccountConnections } else if kind == LEAF && acc.MaxTotalLeafNodesReached() { return ErrTooManyAccountConnections } // Add in new one. if prev := acc.addClient(c); prev == 0 && srv != nil { srv.incActiveAccounts() } return nil }
go
func (c *client) registerWithAccount(acc *Account) error { if acc == nil || acc.sl == nil { return ErrBadAccount } // If we were previously registered, usually to $G, do accounting here to remove. if c.acc != nil { if prev := c.acc.removeClient(c); prev == 1 && c.srv != nil { c.srv.decActiveAccounts() } } c.mu.Lock() kind := c.kind srv := c.srv c.acc = acc c.applyAccountLimits() c.mu.Unlock() // Check if we have a max connections violation if kind == CLIENT && acc.MaxTotalConnectionsReached() { return ErrTooManyAccountConnections } else if kind == LEAF && acc.MaxTotalLeafNodesReached() { return ErrTooManyAccountConnections } // Add in new one. if prev := acc.addClient(c); prev == 0 && srv != nil { srv.incActiveAccounts() } return nil }
[ "func", "(", "c", "*", "client", ")", "registerWithAccount", "(", "acc", "*", "Account", ")", "error", "{", "if", "acc", "==", "nil", "||", "acc", ".", "sl", "==", "nil", "{", "return", "ErrBadAccount", "\n", "}", "\n", "// If we were previously registered, usually to $G, do accounting here to remove.", "if", "c", ".", "acc", "!=", "nil", "{", "if", "prev", ":=", "c", ".", "acc", ".", "removeClient", "(", "c", ")", ";", "prev", "==", "1", "&&", "c", ".", "srv", "!=", "nil", "{", "c", ".", "srv", ".", "decActiveAccounts", "(", ")", "\n", "}", "\n", "}", "\n\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "kind", ":=", "c", ".", "kind", "\n", "srv", ":=", "c", ".", "srv", "\n", "c", ".", "acc", "=", "acc", "\n", "c", ".", "applyAccountLimits", "(", ")", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Check if we have a max connections violation", "if", "kind", "==", "CLIENT", "&&", "acc", ".", "MaxTotalConnectionsReached", "(", ")", "{", "return", "ErrTooManyAccountConnections", "\n", "}", "else", "if", "kind", "==", "LEAF", "&&", "acc", ".", "MaxTotalLeafNodesReached", "(", ")", "{", "return", "ErrTooManyAccountConnections", "\n", "}", "\n\n", "// Add in new one.", "if", "prev", ":=", "acc", ".", "addClient", "(", "c", ")", ";", "prev", "==", "0", "&&", "srv", "!=", "nil", "{", "srv", ".", "incActiveAccounts", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// registerWithAccount will register the given user with a specific // account. This will change the subject namespace.
[ "registerWithAccount", "will", "register", "the", "given", "user", "with", "a", "specific", "account", ".", "This", "will", "change", "the", "subject", "namespace", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L438-L469
164,134
nats-io/gnatsd
server/client.go
subsAtLimit
func (c *client) subsAtLimit() bool { return c.msubs != jwt.NoLimit && len(c.subs) >= int(c.msubs) }
go
func (c *client) subsAtLimit() bool { return c.msubs != jwt.NoLimit && len(c.subs) >= int(c.msubs) }
[ "func", "(", "c", "*", "client", ")", "subsAtLimit", "(", ")", "bool", "{", "return", "c", ".", "msubs", "!=", "jwt", ".", "NoLimit", "&&", "len", "(", "c", ".", "subs", ")", ">=", "int", "(", "c", ".", "msubs", ")", "\n", "}" ]
// Helper to determine if we have met or exceeded max subs.
[ "Helper", "to", "determine", "if", "we", "have", "met", "or", "exceeded", "max", "subs", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L472-L474
164,135
nats-io/gnatsd
server/client.go
RegisterUser
func (c *client) RegisterUser(user *User) { // Register with proper account and sublist. if user.Account != nil { if err := c.registerWithAccount(user.Account); err != nil { c.reportErrRegisterAccount(user.Account, err) return } } c.mu.Lock() defer c.mu.Unlock() // Assign permissions. if user.Permissions == nil { // Reset perms to nil in case client previously had them. c.perms = nil c.mperms = nil return } c.setPermissions(user.Permissions) }
go
func (c *client) RegisterUser(user *User) { // Register with proper account and sublist. if user.Account != nil { if err := c.registerWithAccount(user.Account); err != nil { c.reportErrRegisterAccount(user.Account, err) return } } c.mu.Lock() defer c.mu.Unlock() // Assign permissions. if user.Permissions == nil { // Reset perms to nil in case client previously had them. c.perms = nil c.mperms = nil return } c.setPermissions(user.Permissions) }
[ "func", "(", "c", "*", "client", ")", "RegisterUser", "(", "user", "*", "User", ")", "{", "// Register with proper account and sublist.", "if", "user", ".", "Account", "!=", "nil", "{", "if", "err", ":=", "c", ".", "registerWithAccount", "(", "user", ".", "Account", ")", ";", "err", "!=", "nil", "{", "c", ".", "reportErrRegisterAccount", "(", "user", ".", "Account", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Assign permissions.", "if", "user", ".", "Permissions", "==", "nil", "{", "// Reset perms to nil in case client previously had them.", "c", ".", "perms", "=", "nil", "\n", "c", ".", "mperms", "=", "nil", "\n", "return", "\n", "}", "\n", "c", ".", "setPermissions", "(", "user", ".", "Permissions", ")", "\n", "}" ]
// RegisterUser allows auth to call back into a new client // with the authenticated user. This is used to map // any permissions into the client and setup accounts.
[ "RegisterUser", "allows", "auth", "to", "call", "back", "into", "a", "new", "client", "with", "the", "authenticated", "user", ".", "This", "is", "used", "to", "map", "any", "permissions", "into", "the", "client", "and", "setup", "accounts", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L518-L538
164,136
nats-io/gnatsd
server/client.go
RegisterNkeyUser
func (c *client) RegisterNkeyUser(user *NkeyUser) error { // Register with proper account and sublist. if user.Account != nil { if err := c.registerWithAccount(user.Account); err != nil { c.reportErrRegisterAccount(user.Account, err) return err } } c.mu.Lock() c.user = user // Assign permissions. if user.Permissions == nil { // Reset perms to nil in case client previously had them. c.perms = nil c.mperms = nil } else { c.setPermissions(user.Permissions) } c.mu.Unlock() return nil }
go
func (c *client) RegisterNkeyUser(user *NkeyUser) error { // Register with proper account and sublist. if user.Account != nil { if err := c.registerWithAccount(user.Account); err != nil { c.reportErrRegisterAccount(user.Account, err) return err } } c.mu.Lock() c.user = user // Assign permissions. if user.Permissions == nil { // Reset perms to nil in case client previously had them. c.perms = nil c.mperms = nil } else { c.setPermissions(user.Permissions) } c.mu.Unlock() return nil }
[ "func", "(", "c", "*", "client", ")", "RegisterNkeyUser", "(", "user", "*", "NkeyUser", ")", "error", "{", "// Register with proper account and sublist.", "if", "user", ".", "Account", "!=", "nil", "{", "if", "err", ":=", "c", ".", "registerWithAccount", "(", "user", ".", "Account", ")", ";", "err", "!=", "nil", "{", "c", ".", "reportErrRegisterAccount", "(", "user", ".", "Account", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "c", ".", "user", "=", "user", "\n", "// Assign permissions.", "if", "user", ".", "Permissions", "==", "nil", "{", "// Reset perms to nil in case client previously had them.", "c", ".", "perms", "=", "nil", "\n", "c", ".", "mperms", "=", "nil", "\n", "}", "else", "{", "c", ".", "setPermissions", "(", "user", ".", "Permissions", ")", "\n", "}", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// RegisterNkey allows auth to call back into a new nkey // client with the authenticated user. This is used to map // any permissions into the client and setup accounts.
[ "RegisterNkey", "allows", "auth", "to", "call", "back", "into", "a", "new", "nkey", "client", "with", "the", "authenticated", "user", ".", "This", "is", "used", "to", "map", "any", "permissions", "into", "the", "client", "and", "setup", "accounts", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L543-L564
164,137
nats-io/gnatsd
server/client.go
setPermissions
func (c *client) setPermissions(perms *Permissions) { if perms == nil { return } c.perms = &permissions{} c.perms.pcache = make(map[string]bool) // Loop over publish permissions if perms.Publish != nil { if len(perms.Publish.Allow) > 0 { c.perms.pub.allow = NewSublist() } for _, pubSubject := range perms.Publish.Allow { sub := &subscription{subject: []byte(pubSubject)} c.perms.pub.allow.Insert(sub) } if len(perms.Publish.Deny) > 0 { c.perms.pub.deny = NewSublist() } for _, pubSubject := range perms.Publish.Deny { sub := &subscription{subject: []byte(pubSubject)} c.perms.pub.deny.Insert(sub) } } // Loop over subscribe permissions if perms.Subscribe != nil { if len(perms.Subscribe.Allow) > 0 { c.perms.sub.allow = NewSublist() } for _, subSubject := range perms.Subscribe.Allow { sub := &subscription{subject: []byte(subSubject)} c.perms.sub.allow.Insert(sub) } if len(perms.Subscribe.Deny) > 0 { c.perms.sub.deny = NewSublist() // Also hold onto this array for later. c.darray = perms.Subscribe.Deny } for _, subSubject := range perms.Subscribe.Deny { sub := &subscription{subject: []byte(subSubject)} c.perms.sub.deny.Insert(sub) } } }
go
func (c *client) setPermissions(perms *Permissions) { if perms == nil { return } c.perms = &permissions{} c.perms.pcache = make(map[string]bool) // Loop over publish permissions if perms.Publish != nil { if len(perms.Publish.Allow) > 0 { c.perms.pub.allow = NewSublist() } for _, pubSubject := range perms.Publish.Allow { sub := &subscription{subject: []byte(pubSubject)} c.perms.pub.allow.Insert(sub) } if len(perms.Publish.Deny) > 0 { c.perms.pub.deny = NewSublist() } for _, pubSubject := range perms.Publish.Deny { sub := &subscription{subject: []byte(pubSubject)} c.perms.pub.deny.Insert(sub) } } // Loop over subscribe permissions if perms.Subscribe != nil { if len(perms.Subscribe.Allow) > 0 { c.perms.sub.allow = NewSublist() } for _, subSubject := range perms.Subscribe.Allow { sub := &subscription{subject: []byte(subSubject)} c.perms.sub.allow.Insert(sub) } if len(perms.Subscribe.Deny) > 0 { c.perms.sub.deny = NewSublist() // Also hold onto this array for later. c.darray = perms.Subscribe.Deny } for _, subSubject := range perms.Subscribe.Deny { sub := &subscription{subject: []byte(subSubject)} c.perms.sub.deny.Insert(sub) } } }
[ "func", "(", "c", "*", "client", ")", "setPermissions", "(", "perms", "*", "Permissions", ")", "{", "if", "perms", "==", "nil", "{", "return", "\n", "}", "\n", "c", ".", "perms", "=", "&", "permissions", "{", "}", "\n", "c", ".", "perms", ".", "pcache", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n\n", "// Loop over publish permissions", "if", "perms", ".", "Publish", "!=", "nil", "{", "if", "len", "(", "perms", ".", "Publish", ".", "Allow", ")", ">", "0", "{", "c", ".", "perms", ".", "pub", ".", "allow", "=", "NewSublist", "(", ")", "\n", "}", "\n", "for", "_", ",", "pubSubject", ":=", "range", "perms", ".", "Publish", ".", "Allow", "{", "sub", ":=", "&", "subscription", "{", "subject", ":", "[", "]", "byte", "(", "pubSubject", ")", "}", "\n", "c", ".", "perms", ".", "pub", ".", "allow", ".", "Insert", "(", "sub", ")", "\n", "}", "\n", "if", "len", "(", "perms", ".", "Publish", ".", "Deny", ")", ">", "0", "{", "c", ".", "perms", ".", "pub", ".", "deny", "=", "NewSublist", "(", ")", "\n", "}", "\n", "for", "_", ",", "pubSubject", ":=", "range", "perms", ".", "Publish", ".", "Deny", "{", "sub", ":=", "&", "subscription", "{", "subject", ":", "[", "]", "byte", "(", "pubSubject", ")", "}", "\n", "c", ".", "perms", ".", "pub", ".", "deny", ".", "Insert", "(", "sub", ")", "\n", "}", "\n", "}", "\n\n", "// Loop over subscribe permissions", "if", "perms", ".", "Subscribe", "!=", "nil", "{", "if", "len", "(", "perms", ".", "Subscribe", ".", "Allow", ")", ">", "0", "{", "c", ".", "perms", ".", "sub", ".", "allow", "=", "NewSublist", "(", ")", "\n", "}", "\n", "for", "_", ",", "subSubject", ":=", "range", "perms", ".", "Subscribe", ".", "Allow", "{", "sub", ":=", "&", "subscription", "{", "subject", ":", "[", "]", "byte", "(", "subSubject", ")", "}", "\n", "c", ".", "perms", ".", "sub", ".", "allow", ".", "Insert", "(", "sub", ")", "\n", "}", "\n", "if", "len", "(", "perms", ".", "Subscribe", ".", "Deny", ")", ">", "0", "{", "c", ".", "perms", ".", "sub", ".", "deny", "=", "NewSublist", "(", ")", "\n", "// Also hold onto this array for later.", "c", ".", "darray", "=", "perms", ".", "Subscribe", ".", "Deny", "\n", "}", "\n", "for", "_", ",", "subSubject", ":=", "range", "perms", ".", "Subscribe", ".", "Deny", "{", "sub", ":=", "&", "subscription", "{", "subject", ":", "[", "]", "byte", "(", "subSubject", ")", "}", "\n", "c", ".", "perms", ".", "sub", ".", "deny", ".", "Insert", "(", "sub", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Initializes client.perms structure. // Lock is held on entry.
[ "Initializes", "client", ".", "perms", "structure", ".", "Lock", "is", "held", "on", "entry", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L568-L612
164,138
nats-io/gnatsd
server/client.go
loadMsgDenyFilter
func (c *client) loadMsgDenyFilter() { c.mperms = &msgDeny{NewSublist(), make(map[string]bool)} for _, sub := range c.darray { c.mperms.deny.Insert(&subscription{subject: []byte(sub)}) } }
go
func (c *client) loadMsgDenyFilter() { c.mperms = &msgDeny{NewSublist(), make(map[string]bool)} for _, sub := range c.darray { c.mperms.deny.Insert(&subscription{subject: []byte(sub)}) } }
[ "func", "(", "c", "*", "client", ")", "loadMsgDenyFilter", "(", ")", "{", "c", ".", "mperms", "=", "&", "msgDeny", "{", "NewSublist", "(", ")", ",", "make", "(", "map", "[", "string", "]", "bool", ")", "}", "\n", "for", "_", ",", "sub", ":=", "range", "c", ".", "darray", "{", "c", ".", "mperms", ".", "deny", ".", "Insert", "(", "&", "subscription", "{", "subject", ":", "[", "]", "byte", "(", "sub", ")", "}", ")", "\n", "}", "\n", "}" ]
// This will load up the deny structure used for filtering delivered // messages based on a deny clause for subscriptions. // Lock should be held.
[ "This", "will", "load", "up", "the", "deny", "structure", "used", "for", "filtering", "delivered", "messages", "based", "on", "a", "deny", "clause", "for", "subscriptions", ".", "Lock", "should", "be", "held", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L631-L636
164,139
nats-io/gnatsd
server/client.go
writeLoop
func (c *client) writeLoop() { defer c.srv.grWG.Done() // Used to check that we did flush from last wake up. waitOk := true // Main loop. Will wait to be signaled and then will use // buffered outbound structure for efficient writev to the underlying socket. for { c.mu.Lock() owtf := c.out.fsp > 0 && c.out.pb < maxBufSize && c.out.fsp < maxFlushPending if waitOk && (c.out.pb == 0 || owtf) && !c.flags.isSet(clearConnection) { // Wait on pending data. c.out.sgw = true c.out.sg.Wait() c.out.sgw = false } // Flush data // TODO(dlc) - This could spin if another go routine in flushOutbound waiting on a slow IO. waitOk = c.flushOutbound() isClosed := c.flags.isSet(clearConnection) c.mu.Unlock() if isClosed { return } } }
go
func (c *client) writeLoop() { defer c.srv.grWG.Done() // Used to check that we did flush from last wake up. waitOk := true // Main loop. Will wait to be signaled and then will use // buffered outbound structure for efficient writev to the underlying socket. for { c.mu.Lock() owtf := c.out.fsp > 0 && c.out.pb < maxBufSize && c.out.fsp < maxFlushPending if waitOk && (c.out.pb == 0 || owtf) && !c.flags.isSet(clearConnection) { // Wait on pending data. c.out.sgw = true c.out.sg.Wait() c.out.sgw = false } // Flush data // TODO(dlc) - This could spin if another go routine in flushOutbound waiting on a slow IO. waitOk = c.flushOutbound() isClosed := c.flags.isSet(clearConnection) c.mu.Unlock() if isClosed { return } } }
[ "func", "(", "c", "*", "client", ")", "writeLoop", "(", ")", "{", "defer", "c", ".", "srv", ".", "grWG", ".", "Done", "(", ")", "\n\n", "// Used to check that we did flush from last wake up.", "waitOk", ":=", "true", "\n\n", "// Main loop. Will wait to be signaled and then will use", "// buffered outbound structure for efficient writev to the underlying socket.", "for", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "owtf", ":=", "c", ".", "out", ".", "fsp", ">", "0", "&&", "c", ".", "out", ".", "pb", "<", "maxBufSize", "&&", "c", ".", "out", ".", "fsp", "<", "maxFlushPending", "\n", "if", "waitOk", "&&", "(", "c", ".", "out", ".", "pb", "==", "0", "||", "owtf", ")", "&&", "!", "c", ".", "flags", ".", "isSet", "(", "clearConnection", ")", "{", "// Wait on pending data.", "c", ".", "out", ".", "sgw", "=", "true", "\n", "c", ".", "out", ".", "sg", ".", "Wait", "(", ")", "\n", "c", ".", "out", ".", "sgw", "=", "false", "\n", "}", "\n", "// Flush data", "// TODO(dlc) - This could spin if another go routine in flushOutbound waiting on a slow IO.", "waitOk", "=", "c", ".", "flushOutbound", "(", ")", "\n", "isClosed", ":=", "c", ".", "flags", ".", "isSet", "(", "clearConnection", ")", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "isClosed", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// writeLoop is the main socket write functionality. // Runs in its own Go routine.
[ "writeLoop", "is", "the", "main", "socket", "write", "functionality", ".", "Runs", "in", "its", "own", "Go", "routine", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L640-L667
164,140
nats-io/gnatsd
server/client.go
flushClients
func (c *client) flushClients(budget time.Duration) time.Time { last := time.Now() // Check pending clients for flush. for cp := range c.pcd { // TODO(dlc) - Wonder if it makes more sense to create a new map? delete(c.pcd, cp) // Queue up a flush for those in the set cp.mu.Lock() // Update last activity for message delivery cp.last = last // Remove ourselves from the pending list. cp.out.fsp-- // Just ignore if this was closed. if cp.flags.isSet(clearConnection) { cp.mu.Unlock() continue } if budget > 0 && cp.flushOutbound() { budget -= cp.out.lft } else { cp.flushSignal() } cp.mu.Unlock() } return last }
go
func (c *client) flushClients(budget time.Duration) time.Time { last := time.Now() // Check pending clients for flush. for cp := range c.pcd { // TODO(dlc) - Wonder if it makes more sense to create a new map? delete(c.pcd, cp) // Queue up a flush for those in the set cp.mu.Lock() // Update last activity for message delivery cp.last = last // Remove ourselves from the pending list. cp.out.fsp-- // Just ignore if this was closed. if cp.flags.isSet(clearConnection) { cp.mu.Unlock() continue } if budget > 0 && cp.flushOutbound() { budget -= cp.out.lft } else { cp.flushSignal() } cp.mu.Unlock() } return last }
[ "func", "(", "c", "*", "client", ")", "flushClients", "(", "budget", "time", ".", "Duration", ")", "time", ".", "Time", "{", "last", ":=", "time", ".", "Now", "(", ")", "\n", "// Check pending clients for flush.", "for", "cp", ":=", "range", "c", ".", "pcd", "{", "// TODO(dlc) - Wonder if it makes more sense to create a new map?", "delete", "(", "c", ".", "pcd", ",", "cp", ")", "\n\n", "// Queue up a flush for those in the set", "cp", ".", "mu", ".", "Lock", "(", ")", "\n", "// Update last activity for message delivery", "cp", ".", "last", "=", "last", "\n", "// Remove ourselves from the pending list.", "cp", ".", "out", ".", "fsp", "--", "\n\n", "// Just ignore if this was closed.", "if", "cp", ".", "flags", ".", "isSet", "(", "clearConnection", ")", "{", "cp", ".", "mu", ".", "Unlock", "(", ")", "\n", "continue", "\n", "}", "\n\n", "if", "budget", ">", "0", "&&", "cp", ".", "flushOutbound", "(", ")", "{", "budget", "-=", "cp", ".", "out", ".", "lft", "\n", "}", "else", "{", "cp", ".", "flushSignal", "(", ")", "\n", "}", "\n\n", "cp", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "return", "last", "\n", "}" ]
// flushClients will make sure to flush any clients we may have // sent to during processing. We pass in a budget as a time.Duration // for how much time to spend in place flushing for this client. This // will normally be called in the readLoop of the client who sent the // message that now is being delivered.
[ "flushClients", "will", "make", "sure", "to", "flush", "any", "clients", "we", "may", "have", "sent", "to", "during", "processing", ".", "We", "pass", "in", "a", "budget", "as", "a", "time", ".", "Duration", "for", "how", "much", "time", "to", "spend", "in", "place", "flushing", "for", "this", "client", ".", "This", "will", "normally", "be", "called", "in", "the", "readLoop", "of", "the", "client", "who", "sent", "the", "message", "that", "now", "is", "being", "delivered", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L674-L703
164,141
nats-io/gnatsd
server/client.go
collapsePtoNB
func (c *client) collapsePtoNB() net.Buffers { if c.out.p != nil { p := c.out.p c.out.p = nil return append(c.out.nb, p) } return c.out.nb }
go
func (c *client) collapsePtoNB() net.Buffers { if c.out.p != nil { p := c.out.p c.out.p = nil return append(c.out.nb, p) } return c.out.nb }
[ "func", "(", "c", "*", "client", ")", "collapsePtoNB", "(", ")", "net", ".", "Buffers", "{", "if", "c", ".", "out", ".", "p", "!=", "nil", "{", "p", ":=", "c", ".", "out", ".", "p", "\n", "c", ".", "out", ".", "p", "=", "nil", "\n", "return", "append", "(", "c", ".", "out", ".", "nb", ",", "p", ")", "\n", "}", "\n", "return", "c", ".", "out", ".", "nb", "\n", "}" ]
// collapsePtoNB will place primary onto nb buffer as needed in prep for WriteTo. // This will return a copy on purpose.
[ "collapsePtoNB", "will", "place", "primary", "onto", "nb", "buffer", "as", "needed", "in", "prep", "for", "WriteTo", ".", "This", "will", "return", "a", "copy", "on", "purpose", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L818-L825
164,142
nats-io/gnatsd
server/client.go
handlePartialWrite
func (c *client) handlePartialWrite(pnb net.Buffers) { nb := c.collapsePtoNB() // The partial needs to be first, so append nb to pnb c.out.nb = append(pnb, nb...) }
go
func (c *client) handlePartialWrite(pnb net.Buffers) { nb := c.collapsePtoNB() // The partial needs to be first, so append nb to pnb c.out.nb = append(pnb, nb...) }
[ "func", "(", "c", "*", "client", ")", "handlePartialWrite", "(", "pnb", "net", ".", "Buffers", ")", "{", "nb", ":=", "c", ".", "collapsePtoNB", "(", ")", "\n", "// The partial needs to be first, so append nb to pnb", "c", ".", "out", ".", "nb", "=", "append", "(", "pnb", ",", "nb", "...", ")", "\n", "}" ]
// This will handle the fixup needed on a partial write. // Assume pending has been already calculated correctly.
[ "This", "will", "handle", "the", "fixup", "needed", "on", "a", "partial", "write", ".", "Assume", "pending", "has", "been", "already", "calculated", "correctly", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L829-L833
164,143
nats-io/gnatsd
server/client.go
flushSignal
func (c *client) flushSignal() bool { if c.out.sgw { c.out.sg.Signal() return true } return false }
go
func (c *client) flushSignal() bool { if c.out.sgw { c.out.sg.Signal() return true } return false }
[ "func", "(", "c", "*", "client", ")", "flushSignal", "(", ")", "bool", "{", "if", "c", ".", "out", ".", "sgw", "{", "c", ".", "out", ".", "sg", ".", "Signal", "(", ")", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// flushSignal will use server to queue the flush IO operation to a pool of flushers. // Lock must be held.
[ "flushSignal", "will", "use", "server", "to", "queue", "the", "flush", "IO", "operation", "to", "a", "pool", "of", "flushers", ".", "Lock", "must", "be", "held", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L988-L994
164,144
nats-io/gnatsd
server/client.go
processInfo
func (c *client) processInfo(arg []byte) error { info := Info{} if err := json.Unmarshal(arg, &info); err != nil { return err } switch c.kind { case ROUTER: c.processRouteInfo(&info) case GATEWAY: c.processGatewayInfo(&info) case LEAF: c.processLeafnodeInfo(&info) } return nil }
go
func (c *client) processInfo(arg []byte) error { info := Info{} if err := json.Unmarshal(arg, &info); err != nil { return err } switch c.kind { case ROUTER: c.processRouteInfo(&info) case GATEWAY: c.processGatewayInfo(&info) case LEAF: c.processLeafnodeInfo(&info) } return nil }
[ "func", "(", "c", "*", "client", ")", "processInfo", "(", "arg", "[", "]", "byte", ")", "error", "{", "info", ":=", "Info", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "arg", ",", "&", "info", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "c", ".", "kind", "{", "case", "ROUTER", ":", "c", ".", "processRouteInfo", "(", "&", "info", ")", "\n", "case", "GATEWAY", ":", "c", ".", "processGatewayInfo", "(", "&", "info", ")", "\n", "case", "LEAF", ":", "c", ".", "processLeafnodeInfo", "(", "&", "info", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Process the information messages from Clients and other Routes.
[ "Process", "the", "information", "messages", "from", "Clients", "and", "other", "Routes", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L1028-L1042
164,145
nats-io/gnatsd
server/client.go
removePassFromTrace
func removePassFromTrace(arg []byte) []byte { if !bytes.Contains(arg, []byte(`pass`)) { return arg } // Take a copy of the connect proto just for the trace message. var _arg [4096]byte buf := append(_arg[:0], arg...) m := passPat.FindAllSubmatchIndex(buf, -1) if len(m) == 0 { return arg } redactedPass := []byte("[REDACTED]") for _, i := range m { if len(i) < 4 { continue } start := i[2] end := i[3] // Replace password substring. buf = append(buf[:start], append(redactedPass, buf[end:]...)...) break } return buf }
go
func removePassFromTrace(arg []byte) []byte { if !bytes.Contains(arg, []byte(`pass`)) { return arg } // Take a copy of the connect proto just for the trace message. var _arg [4096]byte buf := append(_arg[:0], arg...) m := passPat.FindAllSubmatchIndex(buf, -1) if len(m) == 0 { return arg } redactedPass := []byte("[REDACTED]") for _, i := range m { if len(i) < 4 { continue } start := i[2] end := i[3] // Replace password substring. buf = append(buf[:start], append(redactedPass, buf[end:]...)...) break } return buf }
[ "func", "removePassFromTrace", "(", "arg", "[", "]", "byte", ")", "[", "]", "byte", "{", "if", "!", "bytes", ".", "Contains", "(", "arg", ",", "[", "]", "byte", "(", "`pass`", ")", ")", "{", "return", "arg", "\n", "}", "\n", "// Take a copy of the connect proto just for the trace message.", "var", "_arg", "[", "4096", "]", "byte", "\n", "buf", ":=", "append", "(", "_arg", "[", ":", "0", "]", ",", "arg", "...", ")", "\n\n", "m", ":=", "passPat", ".", "FindAllSubmatchIndex", "(", "buf", ",", "-", "1", ")", "\n", "if", "len", "(", "m", ")", "==", "0", "{", "return", "arg", "\n", "}", "\n\n", "redactedPass", ":=", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "for", "_", ",", "i", ":=", "range", "m", "{", "if", "len", "(", "i", ")", "<", "4", "{", "continue", "\n", "}", "\n", "start", ":=", "i", "[", "2", "]", "\n", "end", ":=", "i", "[", "3", "]", "\n\n", "// Replace password substring.", "buf", "=", "append", "(", "buf", "[", ":", "start", "]", ",", "append", "(", "redactedPass", ",", "buf", "[", "end", ":", "]", "...", ")", "...", ")", "\n", "break", "\n", "}", "\n", "return", "buf", "\n", "}" ]
// removePassFromTrace removes any notion of passwords from trace // messages for logging.
[ "removePassFromTrace", "removes", "any", "notion", "of", "passwords", "from", "trace", "messages", "for", "logging", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L1061-L1087
164,146
nats-io/gnatsd
server/client.go
generateClientInfoJSON
func (c *client) generateClientInfoJSON(info Info) []byte { info.CID = c.cid // Generate the info json b, _ := json.Marshal(info) pcs := [][]byte{[]byte("INFO"), b, []byte(CR_LF)} return bytes.Join(pcs, []byte(" ")) }
go
func (c *client) generateClientInfoJSON(info Info) []byte { info.CID = c.cid // Generate the info json b, _ := json.Marshal(info) pcs := [][]byte{[]byte("INFO"), b, []byte(CR_LF)} return bytes.Join(pcs, []byte(" ")) }
[ "func", "(", "c", "*", "client", ")", "generateClientInfoJSON", "(", "info", "Info", ")", "[", "]", "byte", "{", "info", ".", "CID", "=", "c", ".", "cid", "\n", "// Generate the info json", "b", ",", "_", ":=", "json", ".", "Marshal", "(", "info", ")", "\n", "pcs", ":=", "[", "]", "[", "]", "byte", "{", "[", "]", "byte", "(", "\"", "\"", ")", ",", "b", ",", "[", "]", "byte", "(", "CR_LF", ")", "}", "\n", "return", "bytes", ".", "Join", "(", "pcs", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", "\n", "}" ]
// Generates the INFO to be sent to the client with the client ID included. // info arg will be copied since passed by value. // Assume lock is held.
[ "Generates", "the", "INFO", "to", "be", "sent", "to", "the", "client", "with", "the", "client", "ID", "included", ".", "info", "arg", "will", "be", "copied", "since", "passed", "by", "value", ".", "Assume", "lock", "is", "held", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L1413-L1419
164,147
nats-io/gnatsd
server/client.go
addShadowSubscriptions
func (c *client) addShadowSubscriptions(acc *Account, sub *subscription) error { if acc == nil { return ErrMissingAccount } var ( rims [32]*streamImport ims = rims[:0] rfroms [32]*streamImport froms = rfroms[:0] tokens []string tsa [32]string hasWC bool ) acc.mu.RLock() // Loop over the import subjects. We have 3 scenarios. If we exact // match or we know the proposed subject is a strict subset of the // import we can subscribe to the subscription's subject directly. // The third scenario is where the proposed subject has a wildcard // and may not be an exact subset, but is a match. Therefore we have to // subscribe to the import subject, not the subscription's subject. for _, im := range acc.imports.streams { if im.invalid { continue } subj := string(sub.subject) if subj == im.prefix+im.from { ims = append(ims, im) continue } if tokens == nil { tokens = tsa[:0] start := 0 for i := 0; i < len(subj); i++ { // This is not perfect, but the test below will // be more exact, this is just to trigger the // additional test. if subj[i] == pwc || subj[i] == fwc { hasWC = true } else if subj[i] == btsep { tokens = append(tokens, subj[start:i]) start = i + 1 } } tokens = append(tokens, subj[start:]) } if isSubsetMatch(tokens, im.prefix+im.from) { ims = append(ims, im) } else if hasWC { if subjectIsSubsetMatch(im.prefix+im.from, subj) { froms = append(froms, im) } } } acc.mu.RUnlock() var shadow []*subscription if len(ims) > 0 || len(froms) > 0 { shadow = make([]*subscription, 0, len(ims)+len(froms)) } // Now walk through collected importMaps for _, im := range ims { // We will create a shadow subscription. nsub, err := c.addShadowSub(sub, im, false) if err != nil { return err } shadow = append(shadow, nsub) } // Now walk through importMaps that we need to subscribe // exactly to the "from" property. for _, im := range froms { // We will create a shadow subscription. nsub, err := c.addShadowSub(sub, im, true) if err != nil { return err } shadow = append(shadow, nsub) } if shadow != nil { c.mu.Lock() sub.shadow = shadow c.mu.Unlock() } return nil }
go
func (c *client) addShadowSubscriptions(acc *Account, sub *subscription) error { if acc == nil { return ErrMissingAccount } var ( rims [32]*streamImport ims = rims[:0] rfroms [32]*streamImport froms = rfroms[:0] tokens []string tsa [32]string hasWC bool ) acc.mu.RLock() // Loop over the import subjects. We have 3 scenarios. If we exact // match or we know the proposed subject is a strict subset of the // import we can subscribe to the subscription's subject directly. // The third scenario is where the proposed subject has a wildcard // and may not be an exact subset, but is a match. Therefore we have to // subscribe to the import subject, not the subscription's subject. for _, im := range acc.imports.streams { if im.invalid { continue } subj := string(sub.subject) if subj == im.prefix+im.from { ims = append(ims, im) continue } if tokens == nil { tokens = tsa[:0] start := 0 for i := 0; i < len(subj); i++ { // This is not perfect, but the test below will // be more exact, this is just to trigger the // additional test. if subj[i] == pwc || subj[i] == fwc { hasWC = true } else if subj[i] == btsep { tokens = append(tokens, subj[start:i]) start = i + 1 } } tokens = append(tokens, subj[start:]) } if isSubsetMatch(tokens, im.prefix+im.from) { ims = append(ims, im) } else if hasWC { if subjectIsSubsetMatch(im.prefix+im.from, subj) { froms = append(froms, im) } } } acc.mu.RUnlock() var shadow []*subscription if len(ims) > 0 || len(froms) > 0 { shadow = make([]*subscription, 0, len(ims)+len(froms)) } // Now walk through collected importMaps for _, im := range ims { // We will create a shadow subscription. nsub, err := c.addShadowSub(sub, im, false) if err != nil { return err } shadow = append(shadow, nsub) } // Now walk through importMaps that we need to subscribe // exactly to the "from" property. for _, im := range froms { // We will create a shadow subscription. nsub, err := c.addShadowSub(sub, im, true) if err != nil { return err } shadow = append(shadow, nsub) } if shadow != nil { c.mu.Lock() sub.shadow = shadow c.mu.Unlock() } return nil }
[ "func", "(", "c", "*", "client", ")", "addShadowSubscriptions", "(", "acc", "*", "Account", ",", "sub", "*", "subscription", ")", "error", "{", "if", "acc", "==", "nil", "{", "return", "ErrMissingAccount", "\n", "}", "\n\n", "var", "(", "rims", "[", "32", "]", "*", "streamImport", "\n", "ims", "=", "rims", "[", ":", "0", "]", "\n", "rfroms", "[", "32", "]", "*", "streamImport", "\n", "froms", "=", "rfroms", "[", ":", "0", "]", "\n", "tokens", "[", "]", "string", "\n", "tsa", "[", "32", "]", "string", "\n", "hasWC", "bool", "\n", ")", "\n\n", "acc", ".", "mu", ".", "RLock", "(", ")", "\n", "// Loop over the import subjects. We have 3 scenarios. If we exact", "// match or we know the proposed subject is a strict subset of the", "// import we can subscribe to the subscription's subject directly.", "// The third scenario is where the proposed subject has a wildcard", "// and may not be an exact subset, but is a match. Therefore we have to", "// subscribe to the import subject, not the subscription's subject.", "for", "_", ",", "im", ":=", "range", "acc", ".", "imports", ".", "streams", "{", "if", "im", ".", "invalid", "{", "continue", "\n", "}", "\n", "subj", ":=", "string", "(", "sub", ".", "subject", ")", "\n", "if", "subj", "==", "im", ".", "prefix", "+", "im", ".", "from", "{", "ims", "=", "append", "(", "ims", ",", "im", ")", "\n", "continue", "\n", "}", "\n", "if", "tokens", "==", "nil", "{", "tokens", "=", "tsa", "[", ":", "0", "]", "\n", "start", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "subj", ")", ";", "i", "++", "{", "// This is not perfect, but the test below will", "// be more exact, this is just to trigger the", "// additional test.", "if", "subj", "[", "i", "]", "==", "pwc", "||", "subj", "[", "i", "]", "==", "fwc", "{", "hasWC", "=", "true", "\n", "}", "else", "if", "subj", "[", "i", "]", "==", "btsep", "{", "tokens", "=", "append", "(", "tokens", ",", "subj", "[", "start", ":", "i", "]", ")", "\n", "start", "=", "i", "+", "1", "\n", "}", "\n", "}", "\n", "tokens", "=", "append", "(", "tokens", ",", "subj", "[", "start", ":", "]", ")", "\n", "}", "\n", "if", "isSubsetMatch", "(", "tokens", ",", "im", ".", "prefix", "+", "im", ".", "from", ")", "{", "ims", "=", "append", "(", "ims", ",", "im", ")", "\n", "}", "else", "if", "hasWC", "{", "if", "subjectIsSubsetMatch", "(", "im", ".", "prefix", "+", "im", ".", "from", ",", "subj", ")", "{", "froms", "=", "append", "(", "froms", ",", "im", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "acc", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "var", "shadow", "[", "]", "*", "subscription", "\n\n", "if", "len", "(", "ims", ")", ">", "0", "||", "len", "(", "froms", ")", ">", "0", "{", "shadow", "=", "make", "(", "[", "]", "*", "subscription", ",", "0", ",", "len", "(", "ims", ")", "+", "len", "(", "froms", ")", ")", "\n", "}", "\n\n", "// Now walk through collected importMaps", "for", "_", ",", "im", ":=", "range", "ims", "{", "// We will create a shadow subscription.", "nsub", ",", "err", ":=", "c", ".", "addShadowSub", "(", "sub", ",", "im", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "shadow", "=", "append", "(", "shadow", ",", "nsub", ")", "\n", "}", "\n", "// Now walk through importMaps that we need to subscribe", "// exactly to the \"from\" property.", "for", "_", ",", "im", ":=", "range", "froms", "{", "// We will create a shadow subscription.", "nsub", ",", "err", ":=", "c", ".", "addShadowSub", "(", "sub", ",", "im", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "shadow", "=", "append", "(", "shadow", ",", "nsub", ")", "\n", "}", "\n\n", "if", "shadow", "!=", "nil", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "sub", ".", "shadow", "=", "shadow", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// If the client's account has stream imports and there are matches for // this subscription's subject, then add shadow subscriptions in // other accounts that can export this subject.
[ "If", "the", "client", "s", "account", "has", "stream", "imports", "and", "there", "are", "matches", "for", "this", "subscription", "s", "subject", "then", "add", "shadow", "subscriptions", "in", "other", "accounts", "that", "can", "export", "this", "subject", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L1692-L1782
164,148
nats-io/gnatsd
server/client.go
addShadowSub
func (c *client) addShadowSub(sub *subscription, im *streamImport, useFrom bool) (*subscription, error) { nsub := *sub // copy nsub.im = im if useFrom { nsub.subject = []byte(im.from) } else if im.prefix != "" { // redo subject here to match subject in the publisher account space. // Just remove prefix from what they gave us. That maps into other space. nsub.subject = sub.subject[len(im.prefix):] } c.Debugf("Creating import subscription on %q from account %q", nsub.subject, im.acc.Name) if err := im.acc.sl.Insert(&nsub); err != nil { errs := fmt.Sprintf("Could not add shadow import subscription for account %q", im.acc.Name) c.Debugf(errs) return nil, fmt.Errorf(errs) } // Update our route map here. c.srv.updateRouteSubscriptionMap(im.acc, &nsub, 1) return &nsub, nil }
go
func (c *client) addShadowSub(sub *subscription, im *streamImport, useFrom bool) (*subscription, error) { nsub := *sub // copy nsub.im = im if useFrom { nsub.subject = []byte(im.from) } else if im.prefix != "" { // redo subject here to match subject in the publisher account space. // Just remove prefix from what they gave us. That maps into other space. nsub.subject = sub.subject[len(im.prefix):] } c.Debugf("Creating import subscription on %q from account %q", nsub.subject, im.acc.Name) if err := im.acc.sl.Insert(&nsub); err != nil { errs := fmt.Sprintf("Could not add shadow import subscription for account %q", im.acc.Name) c.Debugf(errs) return nil, fmt.Errorf(errs) } // Update our route map here. c.srv.updateRouteSubscriptionMap(im.acc, &nsub, 1) return &nsub, nil }
[ "func", "(", "c", "*", "client", ")", "addShadowSub", "(", "sub", "*", "subscription", ",", "im", "*", "streamImport", ",", "useFrom", "bool", ")", "(", "*", "subscription", ",", "error", ")", "{", "nsub", ":=", "*", "sub", "// copy", "\n", "nsub", ".", "im", "=", "im", "\n", "if", "useFrom", "{", "nsub", ".", "subject", "=", "[", "]", "byte", "(", "im", ".", "from", ")", "\n", "}", "else", "if", "im", ".", "prefix", "!=", "\"", "\"", "{", "// redo subject here to match subject in the publisher account space.", "// Just remove prefix from what they gave us. That maps into other space.", "nsub", ".", "subject", "=", "sub", ".", "subject", "[", "len", "(", "im", ".", "prefix", ")", ":", "]", "\n", "}", "\n\n", "c", ".", "Debugf", "(", "\"", "\"", ",", "nsub", ".", "subject", ",", "im", ".", "acc", ".", "Name", ")", "\n\n", "if", "err", ":=", "im", ".", "acc", ".", "sl", ".", "Insert", "(", "&", "nsub", ")", ";", "err", "!=", "nil", "{", "errs", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "im", ".", "acc", ".", "Name", ")", "\n", "c", ".", "Debugf", "(", "errs", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "errs", ")", "\n", "}", "\n\n", "// Update our route map here.", "c", ".", "srv", ".", "updateRouteSubscriptionMap", "(", "im", ".", "acc", ",", "&", "nsub", ",", "1", ")", "\n", "return", "&", "nsub", ",", "nil", "\n", "}" ]
// Add in the shadow subscription.
[ "Add", "in", "the", "shadow", "subscription", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L1785-L1807
164,149
nats-io/gnatsd
server/client.go
canSubscribe
func (c *client) canSubscribe(subject string) bool { if c.perms == nil { return true } allowed := true // Check allow list. If no allow list that means all are allowed. Deny can overrule. if c.perms.sub.allow != nil { r := c.perms.sub.allow.Match(subject) allowed = len(r.psubs) != 0 } // If we have a deny list and we think we are allowed, check that as well. if allowed && c.perms.sub.deny != nil { r := c.perms.sub.deny.Match(subject) allowed = len(r.psubs) == 0 // We use the actual subscription to signal us to spin up the deny mperms // and cache. We check if the subject is a wildcard that contains any of // the deny clauses. // FIXME(dlc) - We could be smarter and track when these go away and remove. if allowed && c.mperms == nil && subjectHasWildcard(subject) { // Whip through the deny array and check if this wildcard subject is within scope. for _, sub := range c.darray { tokens := strings.Split(sub, tsep) if isSubsetMatch(tokens, sub) { c.loadMsgDenyFilter() break } } } } return allowed }
go
func (c *client) canSubscribe(subject string) bool { if c.perms == nil { return true } allowed := true // Check allow list. If no allow list that means all are allowed. Deny can overrule. if c.perms.sub.allow != nil { r := c.perms.sub.allow.Match(subject) allowed = len(r.psubs) != 0 } // If we have a deny list and we think we are allowed, check that as well. if allowed && c.perms.sub.deny != nil { r := c.perms.sub.deny.Match(subject) allowed = len(r.psubs) == 0 // We use the actual subscription to signal us to spin up the deny mperms // and cache. We check if the subject is a wildcard that contains any of // the deny clauses. // FIXME(dlc) - We could be smarter and track when these go away and remove. if allowed && c.mperms == nil && subjectHasWildcard(subject) { // Whip through the deny array and check if this wildcard subject is within scope. for _, sub := range c.darray { tokens := strings.Split(sub, tsep) if isSubsetMatch(tokens, sub) { c.loadMsgDenyFilter() break } } } } return allowed }
[ "func", "(", "c", "*", "client", ")", "canSubscribe", "(", "subject", "string", ")", "bool", "{", "if", "c", ".", "perms", "==", "nil", "{", "return", "true", "\n", "}", "\n\n", "allowed", ":=", "true", "\n\n", "// Check allow list. If no allow list that means all are allowed. Deny can overrule.", "if", "c", ".", "perms", ".", "sub", ".", "allow", "!=", "nil", "{", "r", ":=", "c", ".", "perms", ".", "sub", ".", "allow", ".", "Match", "(", "subject", ")", "\n", "allowed", "=", "len", "(", "r", ".", "psubs", ")", "!=", "0", "\n", "}", "\n", "// If we have a deny list and we think we are allowed, check that as well.", "if", "allowed", "&&", "c", ".", "perms", ".", "sub", ".", "deny", "!=", "nil", "{", "r", ":=", "c", ".", "perms", ".", "sub", ".", "deny", ".", "Match", "(", "subject", ")", "\n", "allowed", "=", "len", "(", "r", ".", "psubs", ")", "==", "0", "\n\n", "// We use the actual subscription to signal us to spin up the deny mperms", "// and cache. We check if the subject is a wildcard that contains any of", "// the deny clauses.", "// FIXME(dlc) - We could be smarter and track when these go away and remove.", "if", "allowed", "&&", "c", ".", "mperms", "==", "nil", "&&", "subjectHasWildcard", "(", "subject", ")", "{", "// Whip through the deny array and check if this wildcard subject is within scope.", "for", "_", ",", "sub", ":=", "range", "c", ".", "darray", "{", "tokens", ":=", "strings", ".", "Split", "(", "sub", ",", "tsep", ")", "\n", "if", "isSubsetMatch", "(", "tokens", ",", "sub", ")", "{", "c", ".", "loadMsgDenyFilter", "(", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "allowed", "\n", "}" ]
// canSubscribe determines if the client is authorized to subscribe to the // given subject. Assumes caller is holding lock.
[ "canSubscribe", "determines", "if", "the", "client", "is", "authorized", "to", "subscribe", "to", "the", "given", "subject", ".", "Assumes", "caller", "is", "holding", "lock", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L1811-L1844
164,150
nats-io/gnatsd
server/client.go
unsubscribe
func (c *client) unsubscribe(acc *Account, sub *subscription, force bool) { c.mu.Lock() if !force && sub.max > 0 && sub.nm < sub.max { c.Debugf( "Deferring actual UNSUB(%s): %d max, %d received", string(sub.subject), sub.max, sub.nm) c.mu.Unlock() return } c.traceOp("<-> %s", "DELSUB", sub.sid) delete(c.subs, string(sub.sid)) if c.kind != CLIENT && c.kind != SYSTEM { c.removeReplySubTimeout(sub) } if acc != nil { acc.sl.Remove(sub) } // Check to see if we have shadow subscriptions. var updateRoute bool shadowSubs := sub.shadow sub.shadow = nil if len(shadowSubs) > 0 { updateRoute = (c.kind == CLIENT || c.kind == SYSTEM || c.kind == LEAF) && c.srv != nil } c.mu.Unlock() for _, nsub := range shadowSubs { if err := nsub.im.acc.sl.Remove(nsub); err != nil { c.Debugf("Could not remove shadow import subscription for account %q", nsub.im.acc.Name) } else if updateRoute { c.srv.updateRouteSubscriptionMap(nsub.im.acc, nsub, -1) } // Now check on leafnode updates. c.srv.updateLeafNodes(nsub.im.acc, nsub, -1) } }
go
func (c *client) unsubscribe(acc *Account, sub *subscription, force bool) { c.mu.Lock() if !force && sub.max > 0 && sub.nm < sub.max { c.Debugf( "Deferring actual UNSUB(%s): %d max, %d received", string(sub.subject), sub.max, sub.nm) c.mu.Unlock() return } c.traceOp("<-> %s", "DELSUB", sub.sid) delete(c.subs, string(sub.sid)) if c.kind != CLIENT && c.kind != SYSTEM { c.removeReplySubTimeout(sub) } if acc != nil { acc.sl.Remove(sub) } // Check to see if we have shadow subscriptions. var updateRoute bool shadowSubs := sub.shadow sub.shadow = nil if len(shadowSubs) > 0 { updateRoute = (c.kind == CLIENT || c.kind == SYSTEM || c.kind == LEAF) && c.srv != nil } c.mu.Unlock() for _, nsub := range shadowSubs { if err := nsub.im.acc.sl.Remove(nsub); err != nil { c.Debugf("Could not remove shadow import subscription for account %q", nsub.im.acc.Name) } else if updateRoute { c.srv.updateRouteSubscriptionMap(nsub.im.acc, nsub, -1) } // Now check on leafnode updates. c.srv.updateLeafNodes(nsub.im.acc, nsub, -1) } }
[ "func", "(", "c", "*", "client", ")", "unsubscribe", "(", "acc", "*", "Account", ",", "sub", "*", "subscription", ",", "force", "bool", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "!", "force", "&&", "sub", ".", "max", ">", "0", "&&", "sub", ".", "nm", "<", "sub", ".", "max", "{", "c", ".", "Debugf", "(", "\"", "\"", ",", "string", "(", "sub", ".", "subject", ")", ",", "sub", ".", "max", ",", "sub", ".", "nm", ")", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "c", ".", "traceOp", "(", "\"", "\"", ",", "\"", "\"", ",", "sub", ".", "sid", ")", "\n\n", "delete", "(", "c", ".", "subs", ",", "string", "(", "sub", ".", "sid", ")", ")", "\n", "if", "c", ".", "kind", "!=", "CLIENT", "&&", "c", ".", "kind", "!=", "SYSTEM", "{", "c", ".", "removeReplySubTimeout", "(", "sub", ")", "\n", "}", "\n\n", "if", "acc", "!=", "nil", "{", "acc", ".", "sl", ".", "Remove", "(", "sub", ")", "\n", "}", "\n\n", "// Check to see if we have shadow subscriptions.", "var", "updateRoute", "bool", "\n", "shadowSubs", ":=", "sub", ".", "shadow", "\n", "sub", ".", "shadow", "=", "nil", "\n", "if", "len", "(", "shadowSubs", ")", ">", "0", "{", "updateRoute", "=", "(", "c", ".", "kind", "==", "CLIENT", "||", "c", ".", "kind", "==", "SYSTEM", "||", "c", ".", "kind", "==", "LEAF", ")", "&&", "c", ".", "srv", "!=", "nil", "\n", "}", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "nsub", ":=", "range", "shadowSubs", "{", "if", "err", ":=", "nsub", ".", "im", ".", "acc", ".", "sl", ".", "Remove", "(", "nsub", ")", ";", "err", "!=", "nil", "{", "c", ".", "Debugf", "(", "\"", "\"", ",", "nsub", ".", "im", ".", "acc", ".", "Name", ")", "\n", "}", "else", "if", "updateRoute", "{", "c", ".", "srv", ".", "updateRouteSubscriptionMap", "(", "nsub", ".", "im", ".", "acc", ",", "nsub", ",", "-", "1", ")", "\n", "}", "\n", "// Now check on leafnode updates.", "c", ".", "srv", ".", "updateLeafNodes", "(", "nsub", ".", "im", ".", "acc", ",", "nsub", ",", "-", "1", ")", "\n", "}", "\n", "}" ]
// Low level unsubscribe for a given client.
[ "Low", "level", "unsubscribe", "for", "a", "given", "client", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L1847-L1885
164,151
nats-io/gnatsd
server/client.go
checkDenySub
func (c *client) checkDenySub(subject string) bool { if denied, ok := c.mperms.dcache[subject]; ok { return denied } else if r := c.mperms.deny.Match(subject); len(r.psubs) != 0 { c.mperms.dcache[subject] = true return true } else { c.mperms.dcache[subject] = false } if len(c.mperms.dcache) > maxDenyPermCacheSize { c.pruneDenyCache() } return false }
go
func (c *client) checkDenySub(subject string) bool { if denied, ok := c.mperms.dcache[subject]; ok { return denied } else if r := c.mperms.deny.Match(subject); len(r.psubs) != 0 { c.mperms.dcache[subject] = true return true } else { c.mperms.dcache[subject] = false } if len(c.mperms.dcache) > maxDenyPermCacheSize { c.pruneDenyCache() } return false }
[ "func", "(", "c", "*", "client", ")", "checkDenySub", "(", "subject", "string", ")", "bool", "{", "if", "denied", ",", "ok", ":=", "c", ".", "mperms", ".", "dcache", "[", "subject", "]", ";", "ok", "{", "return", "denied", "\n", "}", "else", "if", "r", ":=", "c", ".", "mperms", ".", "deny", ".", "Match", "(", "subject", ")", ";", "len", "(", "r", ".", "psubs", ")", "!=", "0", "{", "c", ".", "mperms", ".", "dcache", "[", "subject", "]", "=", "true", "\n", "return", "true", "\n", "}", "else", "{", "c", ".", "mperms", ".", "dcache", "[", "subject", "]", "=", "false", "\n", "}", "\n", "if", "len", "(", "c", ".", "mperms", ".", "dcache", ")", ">", "maxDenyPermCacheSize", "{", "c", ".", "pruneDenyCache", "(", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// checkDenySub will check if we are allowed to deliver this message in the // presence of deny clauses for subscriptions. Deny clauses will not prevent // larger scoped wildcard subscriptions, so we need to check at delivery time. // Lock should be held.
[ "checkDenySub", "will", "check", "if", "we", "are", "allowed", "to", "deliver", "this", "message", "in", "the", "presence", "of", "deny", "clauses", "for", "subscriptions", ".", "Deny", "clauses", "will", "not", "prevent", "larger", "scoped", "wildcard", "subscriptions", "so", "we", "need", "to", "check", "at", "delivery", "time", ".", "Lock", "should", "be", "held", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L1954-L1967
164,152
nats-io/gnatsd
server/client.go
pruneDenyCache
func (c *client) pruneDenyCache() { r := 0 for subject := range c.mperms.dcache { delete(c.mperms.dcache, subject) if r++; r > pruneSize { break } } }
go
func (c *client) pruneDenyCache() { r := 0 for subject := range c.mperms.dcache { delete(c.mperms.dcache, subject) if r++; r > pruneSize { break } } }
[ "func", "(", "c", "*", "client", ")", "pruneDenyCache", "(", ")", "{", "r", ":=", "0", "\n", "for", "subject", ":=", "range", "c", ".", "mperms", ".", "dcache", "{", "delete", "(", "c", ".", "mperms", ".", "dcache", ",", "subject", ")", "\n", "if", "r", "++", ";", "r", ">", "pruneSize", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// pruneDenyCache will prune the deny cache via randomly // deleting items. Doing so pruneSize items at a time. // Lock must be held for this one since it is shared under // deliverMsg.
[ "pruneDenyCache", "will", "prune", "the", "deny", "cache", "via", "randomly", "deleting", "items", ".", "Doing", "so", "pruneSize", "items", "at", "a", "time", ".", "Lock", "must", "be", "held", "for", "this", "one", "since", "it", "is", "shared", "under", "deliverMsg", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L2125-L2133
164,153
nats-io/gnatsd
server/client.go
prunePubPermsCache
func (c *client) prunePubPermsCache() { r := 0 for subject := range c.perms.pcache { delete(c.perms.pcache, subject) if r++; r > pruneSize { break } } }
go
func (c *client) prunePubPermsCache() { r := 0 for subject := range c.perms.pcache { delete(c.perms.pcache, subject) if r++; r > pruneSize { break } } }
[ "func", "(", "c", "*", "client", ")", "prunePubPermsCache", "(", ")", "{", "r", ":=", "0", "\n", "for", "subject", ":=", "range", "c", ".", "perms", ".", "pcache", "{", "delete", "(", "c", ".", "perms", ".", "pcache", ",", "subject", ")", "\n", "if", "r", "++", ";", "r", ">", "pruneSize", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// prunePubPermsCache will prune the cache via randomly // deleting items. Doing so pruneSize items at a time.
[ "prunePubPermsCache", "will", "prune", "the", "cache", "via", "randomly", "deleting", "items", ".", "Doing", "so", "pruneSize", "items", "at", "a", "time", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L2137-L2145
164,154
nats-io/gnatsd
server/client.go
pubAllowed
func (c *client) pubAllowed(subject string) bool { if c.perms == nil || (c.perms.pub.allow == nil && c.perms.pub.deny == nil) { return true } // Check if published subject is allowed if we have permissions in place. allowed, ok := c.perms.pcache[subject] if ok { return allowed } // Cache miss, check allow then deny as needed. if c.perms.pub.allow != nil { r := c.perms.pub.allow.Match(subject) allowed = len(r.psubs) != 0 } else { // No entries means all are allowed. Deny will overrule as needed. allowed = true } // If we have a deny list and are currently allowed, check that as well. if allowed && c.perms.pub.deny != nil { r := c.perms.pub.deny.Match(subject) allowed = len(r.psubs) == 0 } // Update our cache here. c.perms.pcache[string(subject)] = allowed // Prune if needed. if len(c.perms.pcache) > maxPermCacheSize { c.prunePubPermsCache() } return allowed }
go
func (c *client) pubAllowed(subject string) bool { if c.perms == nil || (c.perms.pub.allow == nil && c.perms.pub.deny == nil) { return true } // Check if published subject is allowed if we have permissions in place. allowed, ok := c.perms.pcache[subject] if ok { return allowed } // Cache miss, check allow then deny as needed. if c.perms.pub.allow != nil { r := c.perms.pub.allow.Match(subject) allowed = len(r.psubs) != 0 } else { // No entries means all are allowed. Deny will overrule as needed. allowed = true } // If we have a deny list and are currently allowed, check that as well. if allowed && c.perms.pub.deny != nil { r := c.perms.pub.deny.Match(subject) allowed = len(r.psubs) == 0 } // Update our cache here. c.perms.pcache[string(subject)] = allowed // Prune if needed. if len(c.perms.pcache) > maxPermCacheSize { c.prunePubPermsCache() } return allowed }
[ "func", "(", "c", "*", "client", ")", "pubAllowed", "(", "subject", "string", ")", "bool", "{", "if", "c", ".", "perms", "==", "nil", "||", "(", "c", ".", "perms", ".", "pub", ".", "allow", "==", "nil", "&&", "c", ".", "perms", ".", "pub", ".", "deny", "==", "nil", ")", "{", "return", "true", "\n", "}", "\n", "// Check if published subject is allowed if we have permissions in place.", "allowed", ",", "ok", ":=", "c", ".", "perms", ".", "pcache", "[", "subject", "]", "\n", "if", "ok", "{", "return", "allowed", "\n", "}", "\n", "// Cache miss, check allow then deny as needed.", "if", "c", ".", "perms", ".", "pub", ".", "allow", "!=", "nil", "{", "r", ":=", "c", ".", "perms", ".", "pub", ".", "allow", ".", "Match", "(", "subject", ")", "\n", "allowed", "=", "len", "(", "r", ".", "psubs", ")", "!=", "0", "\n", "}", "else", "{", "// No entries means all are allowed. Deny will overrule as needed.", "allowed", "=", "true", "\n", "}", "\n", "// If we have a deny list and are currently allowed, check that as well.", "if", "allowed", "&&", "c", ".", "perms", ".", "pub", ".", "deny", "!=", "nil", "{", "r", ":=", "c", ".", "perms", ".", "pub", ".", "deny", ".", "Match", "(", "subject", ")", "\n", "allowed", "=", "len", "(", "r", ".", "psubs", ")", "==", "0", "\n", "}", "\n", "// Update our cache here.", "c", ".", "perms", ".", "pcache", "[", "string", "(", "subject", ")", "]", "=", "allowed", "\n", "// Prune if needed.", "if", "len", "(", "c", ".", "perms", ".", "pcache", ")", ">", "maxPermCacheSize", "{", "c", ".", "prunePubPermsCache", "(", ")", "\n", "}", "\n", "return", "allowed", "\n", "}" ]
// pubAllowed checks on publish permissioning.
[ "pubAllowed", "checks", "on", "publish", "permissioning", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L2148-L2177
164,155
nats-io/gnatsd
server/client.go
newServiceReply
func (c *client) newServiceReply() []byte { // Check to see if we have our own rand yet. Global rand // has contention with lots of clients, etc. if c.in.prand == nil { c.in.prand = rand.New(rand.NewSource(time.Now().UnixNano())) } var b = [15]byte{'_', 'R', '_', '.'} rn := c.in.prand.Int63() for i, l := replyPrefixLen, rn; i < len(b); i++ { b[i] = digits[l%base] l /= base } return b[:] }
go
func (c *client) newServiceReply() []byte { // Check to see if we have our own rand yet. Global rand // has contention with lots of clients, etc. if c.in.prand == nil { c.in.prand = rand.New(rand.NewSource(time.Now().UnixNano())) } var b = [15]byte{'_', 'R', '_', '.'} rn := c.in.prand.Int63() for i, l := replyPrefixLen, rn; i < len(b); i++ { b[i] = digits[l%base] l /= base } return b[:] }
[ "func", "(", "c", "*", "client", ")", "newServiceReply", "(", ")", "[", "]", "byte", "{", "// Check to see if we have our own rand yet. Global rand", "// has contention with lots of clients, etc.", "if", "c", ".", "in", ".", "prand", "==", "nil", "{", "c", ".", "in", ".", "prand", "=", "rand", ".", "New", "(", "rand", ".", "NewSource", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", ")", "\n", "}", "\n\n", "var", "b", "=", "[", "15", "]", "byte", "{", "'_'", ",", "'R'", ",", "'_'", ",", "'.'", "}", "\n", "rn", ":=", "c", ".", "in", ".", "prand", ".", "Int63", "(", ")", "\n", "for", "i", ",", "l", ":=", "replyPrefixLen", ",", "rn", ";", "i", "<", "len", "(", "b", ")", ";", "i", "++", "{", "b", "[", "i", "]", "=", "digits", "[", "l", "%", "base", "]", "\n", "l", "/=", "base", "\n", "}", "\n", "return", "b", "[", ":", "]", "\n", "}" ]
// newServiceReply is used when rewriting replies that cross account boundaries. // These will look like _R_.XXXXXXXX.
[ "newServiceReply", "is", "used", "when", "rewriting", "replies", "that", "cross", "account", "boundaries", ".", "These", "will", "look", "like", "_R_", ".", "XXXXXXXX", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L2189-L2203
164,156
nats-io/gnatsd
server/client.go
processInboundMsg
func (c *client) processInboundMsg(msg []byte) { switch c.kind { case CLIENT: c.processInboundClientMsg(msg) case ROUTER: c.processInboundRoutedMsg(msg) case GATEWAY: c.processInboundGatewayMsg(msg) case LEAF: c.processInboundLeafMsg(msg) } }
go
func (c *client) processInboundMsg(msg []byte) { switch c.kind { case CLIENT: c.processInboundClientMsg(msg) case ROUTER: c.processInboundRoutedMsg(msg) case GATEWAY: c.processInboundGatewayMsg(msg) case LEAF: c.processInboundLeafMsg(msg) } }
[ "func", "(", "c", "*", "client", ")", "processInboundMsg", "(", "msg", "[", "]", "byte", ")", "{", "switch", "c", ".", "kind", "{", "case", "CLIENT", ":", "c", ".", "processInboundClientMsg", "(", "msg", ")", "\n", "case", "ROUTER", ":", "c", ".", "processInboundRoutedMsg", "(", "msg", ")", "\n", "case", "GATEWAY", ":", "c", ".", "processInboundGatewayMsg", "(", "msg", ")", "\n", "case", "LEAF", ":", "c", ".", "processInboundLeafMsg", "(", "msg", ")", "\n", "}", "\n", "}" ]
// This will decide to call the client code or router code.
[ "This", "will", "decide", "to", "call", "the", "client", "code", "or", "router", "code", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L2211-L2222
164,157
nats-io/gnatsd
server/client.go
checkForImportServices
func (c *client) checkForImportServices(acc *Account, msg []byte) { if acc == nil || acc.imports.services == nil { return } acc.mu.RLock() rm := acc.imports.services[string(c.pa.subject)] invalid := rm != nil && rm.invalid acc.mu.RUnlock() // Get the results from the other account for the mapped "to" subject. // If we have been marked invalid simply return here. if rm != nil && !invalid && rm.acc != nil && rm.acc.sl != nil { var nrr []byte if rm.ae { acc.removeServiceImport(rm.from) } if c.pa.reply != nil { // We want to remap this to provide anonymity. nrr = c.newServiceReply() rm.acc.addImplicitServiceImport(acc, string(nrr), string(c.pa.reply), true, nil) // If this is a client connection and we are in // gateway mode, we need to send RS+ to local cluster // and possibly to inbound GW connections for // which we are in interest-only mode. if c.kind == CLIENT && c.srv.gateway.enabled { c.srv.gatewayHandleServiceImport(rm.acc, nrr, c, 1) } } // FIXME(dlc) - Do L1 cache trick from above. rr := rm.acc.sl.Match(rm.to) // If we are a route or gateway and this message is flipped to a queue subscriber we // need to handle that since the processMsgResults will want a queue filter. if (c.kind == ROUTER || c.kind == GATEWAY) && c.pa.queues == nil && len(rr.qsubs) > 0 { c.makeQFilter(rr.qsubs) } // If this is not a gateway connection but gateway is enabled, // try to send this converted message to all gateways. if c.srv.gateway.enabled && (c.kind == CLIENT || c.kind == SYSTEM || c.kind == LEAF) { queues := c.processMsgResults(rm.acc, rr, msg, []byte(rm.to), nrr, pmrCollectQueueNames) c.sendMsgToGateways(rm.acc, msg, []byte(rm.to), nrr, queues) } else { c.processMsgResults(rm.acc, rr, msg, []byte(rm.to), nrr, pmrNoFlag) } } }
go
func (c *client) checkForImportServices(acc *Account, msg []byte) { if acc == nil || acc.imports.services == nil { return } acc.mu.RLock() rm := acc.imports.services[string(c.pa.subject)] invalid := rm != nil && rm.invalid acc.mu.RUnlock() // Get the results from the other account for the mapped "to" subject. // If we have been marked invalid simply return here. if rm != nil && !invalid && rm.acc != nil && rm.acc.sl != nil { var nrr []byte if rm.ae { acc.removeServiceImport(rm.from) } if c.pa.reply != nil { // We want to remap this to provide anonymity. nrr = c.newServiceReply() rm.acc.addImplicitServiceImport(acc, string(nrr), string(c.pa.reply), true, nil) // If this is a client connection and we are in // gateway mode, we need to send RS+ to local cluster // and possibly to inbound GW connections for // which we are in interest-only mode. if c.kind == CLIENT && c.srv.gateway.enabled { c.srv.gatewayHandleServiceImport(rm.acc, nrr, c, 1) } } // FIXME(dlc) - Do L1 cache trick from above. rr := rm.acc.sl.Match(rm.to) // If we are a route or gateway and this message is flipped to a queue subscriber we // need to handle that since the processMsgResults will want a queue filter. if (c.kind == ROUTER || c.kind == GATEWAY) && c.pa.queues == nil && len(rr.qsubs) > 0 { c.makeQFilter(rr.qsubs) } // If this is not a gateway connection but gateway is enabled, // try to send this converted message to all gateways. if c.srv.gateway.enabled && (c.kind == CLIENT || c.kind == SYSTEM || c.kind == LEAF) { queues := c.processMsgResults(rm.acc, rr, msg, []byte(rm.to), nrr, pmrCollectQueueNames) c.sendMsgToGateways(rm.acc, msg, []byte(rm.to), nrr, queues) } else { c.processMsgResults(rm.acc, rr, msg, []byte(rm.to), nrr, pmrNoFlag) } } }
[ "func", "(", "c", "*", "client", ")", "checkForImportServices", "(", "acc", "*", "Account", ",", "msg", "[", "]", "byte", ")", "{", "if", "acc", "==", "nil", "||", "acc", ".", "imports", ".", "services", "==", "nil", "{", "return", "\n", "}", "\n", "acc", ".", "mu", ".", "RLock", "(", ")", "\n", "rm", ":=", "acc", ".", "imports", ".", "services", "[", "string", "(", "c", ".", "pa", ".", "subject", ")", "]", "\n", "invalid", ":=", "rm", "!=", "nil", "&&", "rm", ".", "invalid", "\n", "acc", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "// Get the results from the other account for the mapped \"to\" subject.", "// If we have been marked invalid simply return here.", "if", "rm", "!=", "nil", "&&", "!", "invalid", "&&", "rm", ".", "acc", "!=", "nil", "&&", "rm", ".", "acc", ".", "sl", "!=", "nil", "{", "var", "nrr", "[", "]", "byte", "\n", "if", "rm", ".", "ae", "{", "acc", ".", "removeServiceImport", "(", "rm", ".", "from", ")", "\n", "}", "\n", "if", "c", ".", "pa", ".", "reply", "!=", "nil", "{", "// We want to remap this to provide anonymity.", "nrr", "=", "c", ".", "newServiceReply", "(", ")", "\n", "rm", ".", "acc", ".", "addImplicitServiceImport", "(", "acc", ",", "string", "(", "nrr", ")", ",", "string", "(", "c", ".", "pa", ".", "reply", ")", ",", "true", ",", "nil", ")", "\n", "// If this is a client connection and we are in", "// gateway mode, we need to send RS+ to local cluster", "// and possibly to inbound GW connections for", "// which we are in interest-only mode.", "if", "c", ".", "kind", "==", "CLIENT", "&&", "c", ".", "srv", ".", "gateway", ".", "enabled", "{", "c", ".", "srv", ".", "gatewayHandleServiceImport", "(", "rm", ".", "acc", ",", "nrr", ",", "c", ",", "1", ")", "\n", "}", "\n", "}", "\n", "// FIXME(dlc) - Do L1 cache trick from above.", "rr", ":=", "rm", ".", "acc", ".", "sl", ".", "Match", "(", "rm", ".", "to", ")", "\n\n", "// If we are a route or gateway and this message is flipped to a queue subscriber we", "// need to handle that since the processMsgResults will want a queue filter.", "if", "(", "c", ".", "kind", "==", "ROUTER", "||", "c", ".", "kind", "==", "GATEWAY", ")", "&&", "c", ".", "pa", ".", "queues", "==", "nil", "&&", "len", "(", "rr", ".", "qsubs", ")", ">", "0", "{", "c", ".", "makeQFilter", "(", "rr", ".", "qsubs", ")", "\n", "}", "\n\n", "// If this is not a gateway connection but gateway is enabled,", "// try to send this converted message to all gateways.", "if", "c", ".", "srv", ".", "gateway", ".", "enabled", "&&", "(", "c", ".", "kind", "==", "CLIENT", "||", "c", ".", "kind", "==", "SYSTEM", "||", "c", ".", "kind", "==", "LEAF", ")", "{", "queues", ":=", "c", ".", "processMsgResults", "(", "rm", ".", "acc", ",", "rr", ",", "msg", ",", "[", "]", "byte", "(", "rm", ".", "to", ")", ",", "nrr", ",", "pmrCollectQueueNames", ")", "\n", "c", ".", "sendMsgToGateways", "(", "rm", ".", "acc", ",", "msg", ",", "[", "]", "byte", "(", "rm", ".", "to", ")", ",", "nrr", ",", "queues", ")", "\n", "}", "else", "{", "c", ".", "processMsgResults", "(", "rm", ".", "acc", ",", "rr", ",", "msg", ",", "[", "]", "byte", "(", "rm", ".", "to", ")", ",", "nrr", ",", "pmrNoFlag", ")", "\n", "}", "\n", "}", "\n", "}" ]
// This checks and process import services by doing the mapping and sending the // message onward if applicable.
[ "This", "checks", "and", "process", "import", "services", "by", "doing", "the", "mapping", "and", "sending", "the", "message", "onward", "if", "applicable", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L2316-L2362
164,158
nats-io/gnatsd
server/client.go
awaitingAuth
func (c *client) awaitingAuth() bool { return !c.flags.isSet(connectReceived) && c.atmr != nil }
go
func (c *client) awaitingAuth() bool { return !c.flags.isSet(connectReceived) && c.atmr != nil }
[ "func", "(", "c", "*", "client", ")", "awaitingAuth", "(", ")", "bool", "{", "return", "!", "c", ".", "flags", ".", "isSet", "(", "connectReceived", ")", "&&", "c", ".", "atmr", "!=", "nil", "\n", "}" ]
// We may reuse atmr for expiring user jwts, // so check connectReceived. // Lock assume held on entry.
[ "We", "may", "reuse", "atmr", "for", "expiring", "user", "jwts", "so", "check", "connectReceived", ".", "Lock", "assume", "held", "on", "entry", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L2682-L2684
164,159
nats-io/gnatsd
server/client.go
setExpirationTimer
func (c *client) setExpirationTimer(d time.Duration) { c.mu.Lock() c.atmr = time.AfterFunc(d, c.authExpired) c.mu.Unlock() }
go
func (c *client) setExpirationTimer(d time.Duration) { c.mu.Lock() c.atmr = time.AfterFunc(d, c.authExpired) c.mu.Unlock() }
[ "func", "(", "c", "*", "client", ")", "setExpirationTimer", "(", "d", "time", ".", "Duration", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "c", ".", "atmr", "=", "time", ".", "AfterFunc", "(", "d", ",", "c", ".", "authExpired", ")", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// This will set the atmr for the JWT expiration time. // We will lock on entry.
[ "This", "will", "set", "the", "atmr", "for", "the", "JWT", "expiration", "time", ".", "We", "will", "lock", "on", "entry", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L2688-L2692
164,160
nats-io/gnatsd
server/client.go
getRTTValue
func (c *client) getRTTValue() time.Duration { c.mu.Lock() rtt := c.rtt c.mu.Unlock() return rtt }
go
func (c *client) getRTTValue() time.Duration { c.mu.Lock() rtt := c.rtt c.mu.Unlock() return rtt }
[ "func", "(", "c", "*", "client", ")", "getRTTValue", "(", ")", "time", ".", "Duration", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "rtt", ":=", "c", ".", "rtt", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "rtt", "\n", "}" ]
// Returns the client's RTT value with the protection of the client's lock.
[ "Returns", "the", "client", "s", "RTT", "value", "with", "the", "protection", "of", "the", "client", "s", "lock", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L2995-L3000
164,161
nats-io/gnatsd
server/client.go
Account
func (c *client) Account() *Account { if c == nil { return nil } c.mu.Lock() defer c.mu.Unlock() return c.acc }
go
func (c *client) Account() *Account { if c == nil { return nil } c.mu.Lock() defer c.mu.Unlock() return c.acc }
[ "func", "(", "c", "*", "client", ")", "Account", "(", ")", "*", "Account", "{", "if", "c", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "acc", "\n", "}" ]
// Account will return the associated account for this client.
[ "Account", "will", "return", "the", "associated", "account", "for", "this", "client", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L3048-L3055
164,162
nats-io/gnatsd
server/client.go
prunePerAccountCache
func (c *client) prunePerAccountCache() { n := 0 for cacheKey := range c.in.pacache { delete(c.in.pacache, cacheKey) if n++; n > prunePerAccountCacheSize { break } } }
go
func (c *client) prunePerAccountCache() { n := 0 for cacheKey := range c.in.pacache { delete(c.in.pacache, cacheKey) if n++; n > prunePerAccountCacheSize { break } } }
[ "func", "(", "c", "*", "client", ")", "prunePerAccountCache", "(", ")", "{", "n", ":=", "0", "\n", "for", "cacheKey", ":=", "range", "c", ".", "in", ".", "pacache", "{", "delete", "(", "c", ".", "in", ".", "pacache", ",", "cacheKey", ")", "\n", "if", "n", "++", ";", "n", ">", "prunePerAccountCacheSize", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// prunePerAccountCache will prune off a random number of cache entries.
[ "prunePerAccountCache", "will", "prune", "off", "a", "random", "number", "of", "cache", "entries", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L3058-L3066
164,163
nats-io/gnatsd
server/client.go
getAuthUser
func (c *client) getAuthUser() string { switch { case c.opts.Nkey != "": return fmt.Sprintf("Nkey %q", c.opts.Nkey) case c.opts.Username != "": return fmt.Sprintf("User %q", c.opts.Username) default: return `User "N/A"` } }
go
func (c *client) getAuthUser() string { switch { case c.opts.Nkey != "": return fmt.Sprintf("Nkey %q", c.opts.Nkey) case c.opts.Username != "": return fmt.Sprintf("User %q", c.opts.Username) default: return `User "N/A"` } }
[ "func", "(", "c", "*", "client", ")", "getAuthUser", "(", ")", "string", "{", "switch", "{", "case", "c", ".", "opts", ".", "Nkey", "!=", "\"", "\"", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "opts", ".", "Nkey", ")", "\n", "case", "c", ".", "opts", ".", "Username", "!=", "\"", "\"", ":", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "opts", ".", "Username", ")", "\n", "default", ":", "return", "`User \"N/A\"`", "\n", "}", "\n", "}" ]
// getAuthUser returns the auth user for the client.
[ "getAuthUser", "returns", "the", "auth", "user", "for", "the", "client", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/client.go#L3069-L3078
164,164
nats-io/gnatsd
server/signal_windows.go
ProcessSignal
func ProcessSignal(command Command, service string) error { if service == "" { service = serviceName } m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(service) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer s.Close() var ( cmd svc.Cmd to svc.State ) switch command { case CommandStop, CommandQuit: cmd = svc.Stop to = svc.Stopped case CommandReopen: cmd = reopenLogCmd to = svc.Running case CommandReload: cmd = svc.ParamChange to = svc.Running case commandLDMode: cmd = ldmCmd to = svc.Running default: return fmt.Errorf("unknown signal %q", command) } status, err := s.Control(cmd) if err != nil { return fmt.Errorf("could not send control=%d: %v", cmd, err) } timeout := time.Now().Add(10 * time.Second) for status.State != to { if timeout.Before(time.Now()) { return fmt.Errorf("timeout waiting for service to go to state=%d", to) } time.Sleep(300 * time.Millisecond) status, err = s.Query() if err != nil { return fmt.Errorf("could not retrieve service status: %v", err) } } return nil }
go
func ProcessSignal(command Command, service string) error { if service == "" { service = serviceName } m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(service) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer s.Close() var ( cmd svc.Cmd to svc.State ) switch command { case CommandStop, CommandQuit: cmd = svc.Stop to = svc.Stopped case CommandReopen: cmd = reopenLogCmd to = svc.Running case CommandReload: cmd = svc.ParamChange to = svc.Running case commandLDMode: cmd = ldmCmd to = svc.Running default: return fmt.Errorf("unknown signal %q", command) } status, err := s.Control(cmd) if err != nil { return fmt.Errorf("could not send control=%d: %v", cmd, err) } timeout := time.Now().Add(10 * time.Second) for status.State != to { if timeout.Before(time.Now()) { return fmt.Errorf("timeout waiting for service to go to state=%d", to) } time.Sleep(300 * time.Millisecond) status, err = s.Query() if err != nil { return fmt.Errorf("could not retrieve service status: %v", err) } } return nil }
[ "func", "ProcessSignal", "(", "command", "Command", ",", "service", "string", ")", "error", "{", "if", "service", "==", "\"", "\"", "{", "service", "=", "serviceName", "\n", "}", "\n\n", "m", ",", "err", ":=", "mgr", ".", "Connect", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "m", ".", "Disconnect", "(", ")", "\n\n", "s", ",", "err", ":=", "m", ".", "OpenService", "(", "service", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "s", ".", "Close", "(", ")", "\n\n", "var", "(", "cmd", "svc", ".", "Cmd", "\n", "to", "svc", ".", "State", "\n", ")", "\n\n", "switch", "command", "{", "case", "CommandStop", ",", "CommandQuit", ":", "cmd", "=", "svc", ".", "Stop", "\n", "to", "=", "svc", ".", "Stopped", "\n", "case", "CommandReopen", ":", "cmd", "=", "reopenLogCmd", "\n", "to", "=", "svc", ".", "Running", "\n", "case", "CommandReload", ":", "cmd", "=", "svc", ".", "ParamChange", "\n", "to", "=", "svc", ".", "Running", "\n", "case", "commandLDMode", ":", "cmd", "=", "ldmCmd", "\n", "to", "=", "svc", ".", "Running", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "command", ")", "\n", "}", "\n\n", "status", ",", "err", ":=", "s", ".", "Control", "(", "cmd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cmd", ",", "err", ")", "\n", "}", "\n\n", "timeout", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "10", "*", "time", ".", "Second", ")", "\n", "for", "status", ".", "State", "!=", "to", "{", "if", "timeout", ".", "Before", "(", "time", ".", "Now", "(", ")", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "to", ")", "\n", "}", "\n", "time", ".", "Sleep", "(", "300", "*", "time", ".", "Millisecond", ")", "\n", "status", ",", "err", "=", "s", ".", "Query", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ProcessSignal sends the given signal command to the running gnatsd service. // If service is empty, this signals the "gnatsd" service. This returns an // error is the given service is not running or the command is invalid.
[ "ProcessSignal", "sends", "the", "given", "signal", "command", "to", "the", "running", "gnatsd", "service", ".", "If", "service", "is", "empty", "this", "signals", "the", "gnatsd", "service", ".", "This", "returns", "an", "error", "is", "the", "given", "service", "is", "not", "running", "or", "the", "command", "is", "invalid", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/signal_windows.go#L47-L104
164,165
nats-io/gnatsd
server/pse/pse_darwin.go
ProcUsage
func ProcUsage(pcpu *float64, rss, vss *int64) error { pidStr := fmt.Sprintf("%d", os.Getpid()) out, err := exec.Command("ps", "o", "pcpu=,rss=,vsz=", "-p", pidStr).Output() if err != nil { *rss, *vss = -1, -1 return fmt.Errorf("ps call failed:%v", err) } fmt.Sscanf(string(out), "%f %d %d", pcpu, rss, vss) *rss *= 1024 // 1k blocks, want bytes. *vss *= 1024 // 1k blocks, want bytes. return nil }
go
func ProcUsage(pcpu *float64, rss, vss *int64) error { pidStr := fmt.Sprintf("%d", os.Getpid()) out, err := exec.Command("ps", "o", "pcpu=,rss=,vsz=", "-p", pidStr).Output() if err != nil { *rss, *vss = -1, -1 return fmt.Errorf("ps call failed:%v", err) } fmt.Sscanf(string(out), "%f %d %d", pcpu, rss, vss) *rss *= 1024 // 1k blocks, want bytes. *vss *= 1024 // 1k blocks, want bytes. return nil }
[ "func", "ProcUsage", "(", "pcpu", "*", "float64", ",", "rss", ",", "vss", "*", "int64", ")", "error", "{", "pidStr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "os", ".", "Getpid", "(", ")", ")", "\n", "out", ",", "err", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "pidStr", ")", ".", "Output", "(", ")", "\n", "if", "err", "!=", "nil", "{", "*", "rss", ",", "*", "vss", "=", "-", "1", ",", "-", "1", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "fmt", ".", "Sscanf", "(", "string", "(", "out", ")", ",", "\"", "\"", ",", "pcpu", ",", "rss", ",", "vss", ")", "\n", "*", "rss", "*=", "1024", "// 1k blocks, want bytes.", "\n", "*", "vss", "*=", "1024", "// 1k blocks, want bytes.", "\n", "return", "nil", "\n", "}" ]
// ProcUsage returns CPU usage
[ "ProcUsage", "returns", "CPU", "usage" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/pse/pse_darwin.go#L23-L34
164,166
nats-io/gnatsd
server/gateway.go
clone
func (r *RemoteGatewayOpts) clone() *RemoteGatewayOpts { if r == nil { return nil } clone := &RemoteGatewayOpts{ Name: r.Name, URLs: deepCopyURLs(r.URLs), } if r.TLSConfig != nil { clone.TLSConfig = r.TLSConfig.Clone() clone.TLSTimeout = r.TLSTimeout } return clone }
go
func (r *RemoteGatewayOpts) clone() *RemoteGatewayOpts { if r == nil { return nil } clone := &RemoteGatewayOpts{ Name: r.Name, URLs: deepCopyURLs(r.URLs), } if r.TLSConfig != nil { clone.TLSConfig = r.TLSConfig.Clone() clone.TLSTimeout = r.TLSTimeout } return clone }
[ "func", "(", "r", "*", "RemoteGatewayOpts", ")", "clone", "(", ")", "*", "RemoteGatewayOpts", "{", "if", "r", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "clone", ":=", "&", "RemoteGatewayOpts", "{", "Name", ":", "r", ".", "Name", ",", "URLs", ":", "deepCopyURLs", "(", "r", ".", "URLs", ")", ",", "}", "\n", "if", "r", ".", "TLSConfig", "!=", "nil", "{", "clone", ".", "TLSConfig", "=", "r", ".", "TLSConfig", ".", "Clone", "(", ")", "\n", "clone", ".", "TLSTimeout", "=", "r", ".", "TLSTimeout", "\n", "}", "\n", "return", "clone", "\n", "}" ]
// clone returns a deep copy of the RemoteGatewayOpts object
[ "clone", "returns", "a", "deep", "copy", "of", "the", "RemoteGatewayOpts", "object" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L188-L201
164,167
nats-io/gnatsd
server/gateway.go
validateGatewayOptions
func validateGatewayOptions(o *Options) error { if o.Gateway.Name == "" && o.Gateway.Port == 0 { return nil } if o.Gateway.Name == "" { return fmt.Errorf("gateway has no name") } if o.Gateway.Port == 0 { return fmt.Errorf("gateway %q has no port specified (select -1 for random port)", o.Gateway.Name) } if o.Gateway.TLSConfig != nil && o.Gateway.TLSConfig.InsecureSkipVerify { return fmt.Errorf("tls InsecureSkipVerify not supported for gateway") } for i, g := range o.Gateway.Gateways { if g.Name == "" { return fmt.Errorf("gateway in the list %d has no name", i) } if len(g.URLs) == 0 { return fmt.Errorf("gateway %q has no URL", g.Name) } if g.TLSConfig != nil && g.TLSConfig.InsecureSkipVerify { return fmt.Errorf("tls InsecureSkipVerify not supported for remote gateway %q", g.Name) } } return nil }
go
func validateGatewayOptions(o *Options) error { if o.Gateway.Name == "" && o.Gateway.Port == 0 { return nil } if o.Gateway.Name == "" { return fmt.Errorf("gateway has no name") } if o.Gateway.Port == 0 { return fmt.Errorf("gateway %q has no port specified (select -1 for random port)", o.Gateway.Name) } if o.Gateway.TLSConfig != nil && o.Gateway.TLSConfig.InsecureSkipVerify { return fmt.Errorf("tls InsecureSkipVerify not supported for gateway") } for i, g := range o.Gateway.Gateways { if g.Name == "" { return fmt.Errorf("gateway in the list %d has no name", i) } if len(g.URLs) == 0 { return fmt.Errorf("gateway %q has no URL", g.Name) } if g.TLSConfig != nil && g.TLSConfig.InsecureSkipVerify { return fmt.Errorf("tls InsecureSkipVerify not supported for remote gateway %q", g.Name) } } return nil }
[ "func", "validateGatewayOptions", "(", "o", "*", "Options", ")", "error", "{", "if", "o", ".", "Gateway", ".", "Name", "==", "\"", "\"", "&&", "o", ".", "Gateway", ".", "Port", "==", "0", "{", "return", "nil", "\n", "}", "\n", "if", "o", ".", "Gateway", ".", "Name", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "o", ".", "Gateway", ".", "Port", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "o", ".", "Gateway", ".", "Name", ")", "\n", "}", "\n", "if", "o", ".", "Gateway", ".", "TLSConfig", "!=", "nil", "&&", "o", ".", "Gateway", ".", "TLSConfig", ".", "InsecureSkipVerify", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ",", "g", ":=", "range", "o", ".", "Gateway", ".", "Gateways", "{", "if", "g", ".", "Name", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "i", ")", "\n", "}", "\n", "if", "len", "(", "g", ".", "URLs", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "g", ".", "Name", ")", "\n", "}", "\n", "if", "g", ".", "TLSConfig", "!=", "nil", "&&", "g", ".", "TLSConfig", ".", "InsecureSkipVerify", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "g", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Ensure that gateway is properly configured.
[ "Ensure", "that", "gateway", "is", "properly", "configured", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L204-L229
164,168
nats-io/gnatsd
server/gateway.go
getReplyPrefixForGateway
func getReplyPrefixForGateway(name string) []byte { sha := sha256.New() sha.Write([]byte(name)) fullHash := []byte(fmt.Sprintf("%x", sha.Sum(nil))) prefix := make([]byte, 0, len(gwReplyPrefix)+5) prefix = append(prefix, gwReplyPrefix...) prefix = append(prefix, fullHash[:4]...) prefix = append(prefix, '.') return prefix }
go
func getReplyPrefixForGateway(name string) []byte { sha := sha256.New() sha.Write([]byte(name)) fullHash := []byte(fmt.Sprintf("%x", sha.Sum(nil))) prefix := make([]byte, 0, len(gwReplyPrefix)+5) prefix = append(prefix, gwReplyPrefix...) prefix = append(prefix, fullHash[:4]...) prefix = append(prefix, '.') return prefix }
[ "func", "getReplyPrefixForGateway", "(", "name", "string", ")", "[", "]", "byte", "{", "sha", ":=", "sha256", ".", "New", "(", ")", "\n", "sha", ".", "Write", "(", "[", "]", "byte", "(", "name", ")", ")", "\n", "fullHash", ":=", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "sha", ".", "Sum", "(", "nil", ")", ")", ")", "\n", "prefix", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "len", "(", "gwReplyPrefix", ")", "+", "5", ")", "\n", "prefix", "=", "append", "(", "prefix", ",", "gwReplyPrefix", "...", ")", "\n", "prefix", "=", "append", "(", "prefix", ",", "fullHash", "[", ":", "4", "]", "...", ")", "\n", "prefix", "=", "append", "(", "prefix", ",", "'.'", ")", "\n", "return", "prefix", "\n", "}" ]
// Computes a hash of 4 characters for the given gateway name. // This will be used for routing of replies.
[ "Computes", "a", "hash", "of", "4", "characters", "for", "the", "given", "gateway", "name", ".", "This", "will", "be", "used", "for", "routing", "of", "replies", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L233-L242
164,169
nats-io/gnatsd
server/gateway.go
newGateway
func newGateway(opts *Options) (*srvGateway, error) { gateway := &srvGateway{ name: opts.Gateway.Name, out: make(map[string]*client), outo: make([]*client, 0, 4), in: make(map[uint64]*client), remotes: make(map[string]*gatewayCfg), URLs: make(map[string]struct{}), resolver: opts.Gateway.resolver, runknown: opts.Gateway.RejectUnknown, replyPfx: getReplyPrefixForGateway(opts.Gateway.Name), } gateway.Lock() defer gateway.Unlock() gateway.pasi.m = make(map[string]map[string]*sitally) if gateway.resolver == nil { gateway.resolver = netResolver(net.DefaultResolver) } // Create remote gateways for _, rgo := range opts.Gateway.Gateways { // Ignore if there is a remote gateway with our name. if rgo.Name == gateway.name { continue } cfg := &gatewayCfg{ RemoteGatewayOpts: rgo.clone(), replyPfx: getReplyPrefixForGateway(rgo.Name), urls: make(map[string]*url.URL, len(rgo.URLs)), } if opts.Gateway.TLSConfig != nil && cfg.TLSConfig == nil { cfg.TLSConfig = opts.Gateway.TLSConfig.Clone() } if cfg.TLSTimeout == 0 { cfg.TLSTimeout = opts.Gateway.TLSTimeout } for _, u := range rgo.URLs { // For TLS, look for a hostname that we can use for TLSConfig.ServerName cfg.saveTLSHostname(u) cfg.urls[u.Host] = u } gateway.remotes[cfg.Name] = cfg } gateway.sqbsz = opts.Gateway.sendQSubsBufSize if gateway.sqbsz == 0 { gateway.sqbsz = maxBufSize } gateway.recSubExp = defaultGatewayRecentSubExpiration gateway.enabled = opts.Gateway.Name != "" && opts.Gateway.Port != 0 return gateway, nil }
go
func newGateway(opts *Options) (*srvGateway, error) { gateway := &srvGateway{ name: opts.Gateway.Name, out: make(map[string]*client), outo: make([]*client, 0, 4), in: make(map[uint64]*client), remotes: make(map[string]*gatewayCfg), URLs: make(map[string]struct{}), resolver: opts.Gateway.resolver, runknown: opts.Gateway.RejectUnknown, replyPfx: getReplyPrefixForGateway(opts.Gateway.Name), } gateway.Lock() defer gateway.Unlock() gateway.pasi.m = make(map[string]map[string]*sitally) if gateway.resolver == nil { gateway.resolver = netResolver(net.DefaultResolver) } // Create remote gateways for _, rgo := range opts.Gateway.Gateways { // Ignore if there is a remote gateway with our name. if rgo.Name == gateway.name { continue } cfg := &gatewayCfg{ RemoteGatewayOpts: rgo.clone(), replyPfx: getReplyPrefixForGateway(rgo.Name), urls: make(map[string]*url.URL, len(rgo.URLs)), } if opts.Gateway.TLSConfig != nil && cfg.TLSConfig == nil { cfg.TLSConfig = opts.Gateway.TLSConfig.Clone() } if cfg.TLSTimeout == 0 { cfg.TLSTimeout = opts.Gateway.TLSTimeout } for _, u := range rgo.URLs { // For TLS, look for a hostname that we can use for TLSConfig.ServerName cfg.saveTLSHostname(u) cfg.urls[u.Host] = u } gateway.remotes[cfg.Name] = cfg } gateway.sqbsz = opts.Gateway.sendQSubsBufSize if gateway.sqbsz == 0 { gateway.sqbsz = maxBufSize } gateway.recSubExp = defaultGatewayRecentSubExpiration gateway.enabled = opts.Gateway.Name != "" && opts.Gateway.Port != 0 return gateway, nil }
[ "func", "newGateway", "(", "opts", "*", "Options", ")", "(", "*", "srvGateway", ",", "error", ")", "{", "gateway", ":=", "&", "srvGateway", "{", "name", ":", "opts", ".", "Gateway", ".", "Name", ",", "out", ":", "make", "(", "map", "[", "string", "]", "*", "client", ")", ",", "outo", ":", "make", "(", "[", "]", "*", "client", ",", "0", ",", "4", ")", ",", "in", ":", "make", "(", "map", "[", "uint64", "]", "*", "client", ")", ",", "remotes", ":", "make", "(", "map", "[", "string", "]", "*", "gatewayCfg", ")", ",", "URLs", ":", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", ",", "resolver", ":", "opts", ".", "Gateway", ".", "resolver", ",", "runknown", ":", "opts", ".", "Gateway", ".", "RejectUnknown", ",", "replyPfx", ":", "getReplyPrefixForGateway", "(", "opts", ".", "Gateway", ".", "Name", ")", ",", "}", "\n", "gateway", ".", "Lock", "(", ")", "\n", "defer", "gateway", ".", "Unlock", "(", ")", "\n\n", "gateway", ".", "pasi", ".", "m", "=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "*", "sitally", ")", "\n\n", "if", "gateway", ".", "resolver", "==", "nil", "{", "gateway", ".", "resolver", "=", "netResolver", "(", "net", ".", "DefaultResolver", ")", "\n", "}", "\n\n", "// Create remote gateways", "for", "_", ",", "rgo", ":=", "range", "opts", ".", "Gateway", ".", "Gateways", "{", "// Ignore if there is a remote gateway with our name.", "if", "rgo", ".", "Name", "==", "gateway", ".", "name", "{", "continue", "\n", "}", "\n", "cfg", ":=", "&", "gatewayCfg", "{", "RemoteGatewayOpts", ":", "rgo", ".", "clone", "(", ")", ",", "replyPfx", ":", "getReplyPrefixForGateway", "(", "rgo", ".", "Name", ")", ",", "urls", ":", "make", "(", "map", "[", "string", "]", "*", "url", ".", "URL", ",", "len", "(", "rgo", ".", "URLs", ")", ")", ",", "}", "\n", "if", "opts", ".", "Gateway", ".", "TLSConfig", "!=", "nil", "&&", "cfg", ".", "TLSConfig", "==", "nil", "{", "cfg", ".", "TLSConfig", "=", "opts", ".", "Gateway", ".", "TLSConfig", ".", "Clone", "(", ")", "\n", "}", "\n", "if", "cfg", ".", "TLSTimeout", "==", "0", "{", "cfg", ".", "TLSTimeout", "=", "opts", ".", "Gateway", ".", "TLSTimeout", "\n", "}", "\n", "for", "_", ",", "u", ":=", "range", "rgo", ".", "URLs", "{", "// For TLS, look for a hostname that we can use for TLSConfig.ServerName", "cfg", ".", "saveTLSHostname", "(", "u", ")", "\n", "cfg", ".", "urls", "[", "u", ".", "Host", "]", "=", "u", "\n", "}", "\n", "gateway", ".", "remotes", "[", "cfg", ".", "Name", "]", "=", "cfg", "\n", "}", "\n\n", "gateway", ".", "sqbsz", "=", "opts", ".", "Gateway", ".", "sendQSubsBufSize", "\n", "if", "gateway", ".", "sqbsz", "==", "0", "{", "gateway", ".", "sqbsz", "=", "maxBufSize", "\n", "}", "\n", "gateway", ".", "recSubExp", "=", "defaultGatewayRecentSubExpiration", "\n\n", "gateway", ".", "enabled", "=", "opts", ".", "Gateway", ".", "Name", "!=", "\"", "\"", "&&", "opts", ".", "Gateway", ".", "Port", "!=", "0", "\n", "return", "gateway", ",", "nil", "\n", "}" ]
// Initialize the s.gateway structure. We do this even if the server // does not have a gateway configured. In some part of the code, the // server will check the number of outbound gateways, etc.. and so // we don't have to check if s.gateway is nil or not.
[ "Initialize", "the", "s", ".", "gateway", "structure", ".", "We", "do", "this", "even", "if", "the", "server", "does", "not", "have", "a", "gateway", "configured", ".", "In", "some", "part", "of", "the", "code", "the", "server", "will", "check", "the", "number", "of", "outbound", "gateways", "etc", "..", "and", "so", "we", "don", "t", "have", "to", "check", "if", "s", ".", "gateway", "is", "nil", "or", "not", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L248-L302
164,170
nats-io/gnatsd
server/gateway.go
getName
func (g *srvGateway) getName() string { g.RLock() n := g.name g.RUnlock() return n }
go
func (g *srvGateway) getName() string { g.RLock() n := g.name g.RUnlock() return n }
[ "func", "(", "g", "*", "srvGateway", ")", "getName", "(", ")", "string", "{", "g", ".", "RLock", "(", ")", "\n", "n", ":=", "g", ".", "name", "\n", "g", ".", "RUnlock", "(", ")", "\n", "return", "n", "\n", "}" ]
// Returns the Gateway's name of this server.
[ "Returns", "the", "Gateway", "s", "name", "of", "this", "server", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L305-L310
164,171
nats-io/gnatsd
server/gateway.go
getURLs
func (g *srvGateway) getURLs() []string { a := make([]string, 0, len(g.URLs)) for u := range g.URLs { a = append(a, u) } return a }
go
func (g *srvGateway) getURLs() []string { a := make([]string, 0, len(g.URLs)) for u := range g.URLs { a = append(a, u) } return a }
[ "func", "(", "g", "*", "srvGateway", ")", "getURLs", "(", ")", "[", "]", "string", "{", "a", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "g", ".", "URLs", ")", ")", "\n", "for", "u", ":=", "range", "g", ".", "URLs", "{", "a", "=", "append", "(", "a", ",", "u", ")", "\n", "}", "\n", "return", "a", "\n", "}" ]
// Returns the Gateway URLs of all servers in the local cluster. // This is used to send to other cluster this server connects to. // The gateway read-lock is held on entry
[ "Returns", "the", "Gateway", "URLs", "of", "all", "servers", "in", "the", "local", "cluster", ".", "This", "is", "used", "to", "send", "to", "other", "cluster", "this", "server", "connects", "to", ".", "The", "gateway", "read", "-", "lock", "is", "held", "on", "entry" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L315-L321
164,172
nats-io/gnatsd
server/gateway.go
rejectUnknown
func (g *srvGateway) rejectUnknown() bool { g.RLock() reject := g.runknown g.RUnlock() return reject }
go
func (g *srvGateway) rejectUnknown() bool { g.RLock() reject := g.runknown g.RUnlock() return reject }
[ "func", "(", "g", "*", "srvGateway", ")", "rejectUnknown", "(", ")", "bool", "{", "g", ".", "RLock", "(", ")", "\n", "reject", ":=", "g", ".", "runknown", "\n", "g", ".", "RUnlock", "(", ")", "\n", "return", "reject", "\n", "}" ]
// Returns if this server rejects connections from gateways that are not // explicitly configured.
[ "Returns", "if", "this", "server", "rejects", "connections", "from", "gateways", "that", "are", "not", "explicitly", "configured", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L325-L330
164,173
nats-io/gnatsd
server/gateway.go
setGatewayInfoHostPort
func (s *Server) setGatewayInfoHostPort(info *Info, o *Options) error { gw := s.gateway gw.Lock() defer gw.Unlock() delete(gw.URLs, gw.URL) if o.Gateway.Advertise != "" { advHost, advPort, err := parseHostPort(o.Gateway.Advertise, o.Gateway.Port) if err != nil { return err } info.Host = advHost info.Port = advPort } else { info.Host = o.Gateway.Host info.Port = o.Gateway.Port // If the host is "0.0.0.0" or "::" we need to resolve to a public IP. // This will return at most 1 IP. hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(info.Host, false) if err != nil { return err } if hostIsIPAny { if len(ips) == 0 { // TODO(ik): Should we fail here (prevent starting)? If not, we // are going to "advertise" the 0.0.0.0:<port> url, which means // that remote are going to try to connect to 0.0.0.0:<port>, // which means a connect to loopback address, which is going // to fail with either TLS error, conn refused if the remote // is using different gateway port than this one, or error // saying that it tried to connect to itself. s.Errorf("Could not find any non-local IP for gateway %q with listen specification %q", gw.name, info.Host) } else { // Take the first from the list... info.Host = ips[0] } } } gw.URL = net.JoinHostPort(info.Host, strconv.Itoa(info.Port)) if o.Gateway.Advertise != "" { s.Noticef("Advertise address for gateway %q is set to %s", gw.name, gw.URL) } else { s.Noticef("Address for gateway %q is %s", gw.name, gw.URL) } gw.URLs[gw.URL] = struct{}{} gw.info = info info.GatewayURL = gw.URL // (re)generate the gatewayInfoJSON byte array gw.generateInfoJSON() return nil }
go
func (s *Server) setGatewayInfoHostPort(info *Info, o *Options) error { gw := s.gateway gw.Lock() defer gw.Unlock() delete(gw.URLs, gw.URL) if o.Gateway.Advertise != "" { advHost, advPort, err := parseHostPort(o.Gateway.Advertise, o.Gateway.Port) if err != nil { return err } info.Host = advHost info.Port = advPort } else { info.Host = o.Gateway.Host info.Port = o.Gateway.Port // If the host is "0.0.0.0" or "::" we need to resolve to a public IP. // This will return at most 1 IP. hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(info.Host, false) if err != nil { return err } if hostIsIPAny { if len(ips) == 0 { // TODO(ik): Should we fail here (prevent starting)? If not, we // are going to "advertise" the 0.0.0.0:<port> url, which means // that remote are going to try to connect to 0.0.0.0:<port>, // which means a connect to loopback address, which is going // to fail with either TLS error, conn refused if the remote // is using different gateway port than this one, or error // saying that it tried to connect to itself. s.Errorf("Could not find any non-local IP for gateway %q with listen specification %q", gw.name, info.Host) } else { // Take the first from the list... info.Host = ips[0] } } } gw.URL = net.JoinHostPort(info.Host, strconv.Itoa(info.Port)) if o.Gateway.Advertise != "" { s.Noticef("Advertise address for gateway %q is set to %s", gw.name, gw.URL) } else { s.Noticef("Address for gateway %q is %s", gw.name, gw.URL) } gw.URLs[gw.URL] = struct{}{} gw.info = info info.GatewayURL = gw.URL // (re)generate the gatewayInfoJSON byte array gw.generateInfoJSON() return nil }
[ "func", "(", "s", "*", "Server", ")", "setGatewayInfoHostPort", "(", "info", "*", "Info", ",", "o", "*", "Options", ")", "error", "{", "gw", ":=", "s", ".", "gateway", "\n", "gw", ".", "Lock", "(", ")", "\n", "defer", "gw", ".", "Unlock", "(", ")", "\n", "delete", "(", "gw", ".", "URLs", ",", "gw", ".", "URL", ")", "\n", "if", "o", ".", "Gateway", ".", "Advertise", "!=", "\"", "\"", "{", "advHost", ",", "advPort", ",", "err", ":=", "parseHostPort", "(", "o", ".", "Gateway", ".", "Advertise", ",", "o", ".", "Gateway", ".", "Port", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "info", ".", "Host", "=", "advHost", "\n", "info", ".", "Port", "=", "advPort", "\n", "}", "else", "{", "info", ".", "Host", "=", "o", ".", "Gateway", ".", "Host", "\n", "info", ".", "Port", "=", "o", ".", "Gateway", ".", "Port", "\n", "// If the host is \"0.0.0.0\" or \"::\" we need to resolve to a public IP.", "// This will return at most 1 IP.", "hostIsIPAny", ",", "ips", ",", "err", ":=", "s", ".", "getNonLocalIPsIfHostIsIPAny", "(", "info", ".", "Host", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "hostIsIPAny", "{", "if", "len", "(", "ips", ")", "==", "0", "{", "// TODO(ik): Should we fail here (prevent starting)? If not, we", "// are going to \"advertise\" the 0.0.0.0:<port> url, which means", "// that remote are going to try to connect to 0.0.0.0:<port>,", "// which means a connect to loopback address, which is going", "// to fail with either TLS error, conn refused if the remote", "// is using different gateway port than this one, or error", "// saying that it tried to connect to itself.", "s", ".", "Errorf", "(", "\"", "\"", ",", "gw", ".", "name", ",", "info", ".", "Host", ")", "\n", "}", "else", "{", "// Take the first from the list...", "info", ".", "Host", "=", "ips", "[", "0", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "gw", ".", "URL", "=", "net", ".", "JoinHostPort", "(", "info", ".", "Host", ",", "strconv", ".", "Itoa", "(", "info", ".", "Port", ")", ")", "\n", "if", "o", ".", "Gateway", ".", "Advertise", "!=", "\"", "\"", "{", "s", ".", "Noticef", "(", "\"", "\"", ",", "gw", ".", "name", ",", "gw", ".", "URL", ")", "\n", "}", "else", "{", "s", ".", "Noticef", "(", "\"", "\"", ",", "gw", ".", "name", ",", "gw", ".", "URL", ")", "\n", "}", "\n", "gw", ".", "URLs", "[", "gw", ".", "URL", "]", "=", "struct", "{", "}", "{", "}", "\n", "gw", ".", "info", "=", "info", "\n", "info", ".", "GatewayURL", "=", "gw", ".", "URL", "\n", "// (re)generate the gatewayInfoJSON byte array", "gw", ".", "generateInfoJSON", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Similar to setInfoHostPortAndGenerateJSON, but for gatewayInfo.
[ "Similar", "to", "setInfoHostPortAndGenerateJSON", "but", "for", "gatewayInfo", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L442-L492
164,174
nats-io/gnatsd
server/gateway.go
generateInfoJSON
func (g *srvGateway) generateInfoJSON() { b, err := json.Marshal(g.info) if err != nil { panic(err) } g.infoJSON = []byte(fmt.Sprintf(InfoProto, b)) }
go
func (g *srvGateway) generateInfoJSON() { b, err := json.Marshal(g.info) if err != nil { panic(err) } g.infoJSON = []byte(fmt.Sprintf(InfoProto, b)) }
[ "func", "(", "g", "*", "srvGateway", ")", "generateInfoJSON", "(", ")", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "g", ".", "info", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "g", ".", "infoJSON", "=", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "InfoProto", ",", "b", ")", ")", "\n", "}" ]
// Generates the Gateway INFO protocol. // The gateway lock is held on entry
[ "Generates", "the", "Gateway", "INFO", "protocol", ".", "The", "gateway", "lock", "is", "held", "on", "entry" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L496-L502
164,175
nats-io/gnatsd
server/gateway.go
reconnectGateway
func (s *Server) reconnectGateway(cfg *gatewayCfg) { defer s.grWG.Done() delay := time.Duration(rand.Intn(100)) * time.Millisecond if !cfg.isImplicit() { delay += gatewayReconnectDelay } select { case <-time.After(delay): case <-s.quitCh: return } s.solicitGateway(cfg) }
go
func (s *Server) reconnectGateway(cfg *gatewayCfg) { defer s.grWG.Done() delay := time.Duration(rand.Intn(100)) * time.Millisecond if !cfg.isImplicit() { delay += gatewayReconnectDelay } select { case <-time.After(delay): case <-s.quitCh: return } s.solicitGateway(cfg) }
[ "func", "(", "s", "*", "Server", ")", "reconnectGateway", "(", "cfg", "*", "gatewayCfg", ")", "{", "defer", "s", ".", "grWG", ".", "Done", "(", ")", "\n\n", "delay", ":=", "time", ".", "Duration", "(", "rand", ".", "Intn", "(", "100", ")", ")", "*", "time", ".", "Millisecond", "\n", "if", "!", "cfg", ".", "isImplicit", "(", ")", "{", "delay", "+=", "gatewayReconnectDelay", "\n", "}", "\n", "select", "{", "case", "<-", "time", ".", "After", "(", "delay", ")", ":", "case", "<-", "s", ".", "quitCh", ":", "return", "\n", "}", "\n", "s", ".", "solicitGateway", "(", "cfg", ")", "\n", "}" ]
// Reconnect to the gateway after a little wait period. For explicit // gateways, we also wait for the default reconnect time.
[ "Reconnect", "to", "the", "gateway", "after", "a", "little", "wait", "period", ".", "For", "explicit", "gateways", "we", "also", "wait", "for", "the", "default", "reconnect", "time", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L529-L542
164,176
nats-io/gnatsd
server/gateway.go
solicitGateway
func (s *Server) solicitGateway(cfg *gatewayCfg) { var ( opts = s.getOpts() isImplicit = cfg.isImplicit() urls = cfg.getURLs() attempts int typeStr string ) if isImplicit { typeStr = "implicit" } else { typeStr = "explicit" } for s.isRunning() && len(urls) > 0 { // Iteration is random for _, u := range urls { address, err := s.getRandomIP(s.gateway.resolver, u.Host) if err != nil { s.Errorf("Error getting IP for %s gateway %q (%s): %v", typeStr, cfg.Name, u.Host, err) continue } s.Noticef("Connecting to %s gateway %q (%s) at %s", typeStr, cfg.Name, u.Host, address) conn, err := net.DialTimeout("tcp", address, DEFAULT_ROUTE_DIAL) if err == nil { // We could connect, create the gateway connection and return. s.createGateway(cfg, u, conn) return } s.Errorf("Error connecting to %s gateway %q (%s) at %s: %v", typeStr, cfg.Name, u.Host, address, err) // Break this loop if server is being shutdown... if !s.isRunning() { break } } if isImplicit { attempts++ if opts.Gateway.ConnectRetries == 0 || attempts > opts.Gateway.ConnectRetries { s.gateway.Lock() delete(s.gateway.remotes, cfg.Name) s.gateway.Unlock() return } } select { case <-s.quitCh: return case <-time.After(gatewayConnectDelay): continue } } }
go
func (s *Server) solicitGateway(cfg *gatewayCfg) { var ( opts = s.getOpts() isImplicit = cfg.isImplicit() urls = cfg.getURLs() attempts int typeStr string ) if isImplicit { typeStr = "implicit" } else { typeStr = "explicit" } for s.isRunning() && len(urls) > 0 { // Iteration is random for _, u := range urls { address, err := s.getRandomIP(s.gateway.resolver, u.Host) if err != nil { s.Errorf("Error getting IP for %s gateway %q (%s): %v", typeStr, cfg.Name, u.Host, err) continue } s.Noticef("Connecting to %s gateway %q (%s) at %s", typeStr, cfg.Name, u.Host, address) conn, err := net.DialTimeout("tcp", address, DEFAULT_ROUTE_DIAL) if err == nil { // We could connect, create the gateway connection and return. s.createGateway(cfg, u, conn) return } s.Errorf("Error connecting to %s gateway %q (%s) at %s: %v", typeStr, cfg.Name, u.Host, address, err) // Break this loop if server is being shutdown... if !s.isRunning() { break } } if isImplicit { attempts++ if opts.Gateway.ConnectRetries == 0 || attempts > opts.Gateway.ConnectRetries { s.gateway.Lock() delete(s.gateway.remotes, cfg.Name) s.gateway.Unlock() return } } select { case <-s.quitCh: return case <-time.After(gatewayConnectDelay): continue } } }
[ "func", "(", "s", "*", "Server", ")", "solicitGateway", "(", "cfg", "*", "gatewayCfg", ")", "{", "var", "(", "opts", "=", "s", ".", "getOpts", "(", ")", "\n", "isImplicit", "=", "cfg", ".", "isImplicit", "(", ")", "\n", "urls", "=", "cfg", ".", "getURLs", "(", ")", "\n", "attempts", "int", "\n", "typeStr", "string", "\n", ")", "\n", "if", "isImplicit", "{", "typeStr", "=", "\"", "\"", "\n", "}", "else", "{", "typeStr", "=", "\"", "\"", "\n", "}", "\n", "for", "s", ".", "isRunning", "(", ")", "&&", "len", "(", "urls", ")", ">", "0", "{", "// Iteration is random", "for", "_", ",", "u", ":=", "range", "urls", "{", "address", ",", "err", ":=", "s", ".", "getRandomIP", "(", "s", ".", "gateway", ".", "resolver", ",", "u", ".", "Host", ")", "\n", "if", "err", "!=", "nil", "{", "s", ".", "Errorf", "(", "\"", "\"", ",", "typeStr", ",", "cfg", ".", "Name", ",", "u", ".", "Host", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "s", ".", "Noticef", "(", "\"", "\"", ",", "typeStr", ",", "cfg", ".", "Name", ",", "u", ".", "Host", ",", "address", ")", "\n", "conn", ",", "err", ":=", "net", ".", "DialTimeout", "(", "\"", "\"", ",", "address", ",", "DEFAULT_ROUTE_DIAL", ")", "\n", "if", "err", "==", "nil", "{", "// We could connect, create the gateway connection and return.", "s", ".", "createGateway", "(", "cfg", ",", "u", ",", "conn", ")", "\n", "return", "\n", "}", "\n", "s", ".", "Errorf", "(", "\"", "\"", ",", "typeStr", ",", "cfg", ".", "Name", ",", "u", ".", "Host", ",", "address", ",", "err", ")", "\n", "// Break this loop if server is being shutdown...", "if", "!", "s", ".", "isRunning", "(", ")", "{", "break", "\n", "}", "\n", "}", "\n", "if", "isImplicit", "{", "attempts", "++", "\n", "if", "opts", ".", "Gateway", ".", "ConnectRetries", "==", "0", "||", "attempts", ">", "opts", ".", "Gateway", ".", "ConnectRetries", "{", "s", ".", "gateway", ".", "Lock", "(", ")", "\n", "delete", "(", "s", ".", "gateway", ".", "remotes", ",", "cfg", ".", "Name", ")", "\n", "s", ".", "gateway", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "select", "{", "case", "<-", "s", ".", "quitCh", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "gatewayConnectDelay", ")", ":", "continue", "\n", "}", "\n", "}", "\n", "}" ]
// This function will loop trying to connect to any URL attached // to the given Gateway. It will return once a connection has been created.
[ "This", "function", "will", "loop", "trying", "to", "connect", "to", "any", "URL", "attached", "to", "the", "given", "Gateway", ".", "It", "will", "return", "once", "a", "connection", "has", "been", "created", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L546-L596
164,177
nats-io/gnatsd
server/gateway.go
sendGatewayConnect
func (c *client) sendGatewayConnect() { tlsRequired := c.gw.cfg.TLSConfig != nil url := c.gw.connectURL c.gw.connectURL = nil var user, pass string if userInfo := url.User; userInfo != nil { user = userInfo.Username() pass, _ = userInfo.Password() } cinfo := connectInfo{ Verbose: false, Pedantic: false, User: user, Pass: pass, TLS: tlsRequired, Name: c.srv.info.ID, Gateway: c.srv.getGatewayName(), } b, err := json.Marshal(cinfo) if err != nil { panic(err) } c.sendProto([]byte(fmt.Sprintf(ConProto, b)), true) }
go
func (c *client) sendGatewayConnect() { tlsRequired := c.gw.cfg.TLSConfig != nil url := c.gw.connectURL c.gw.connectURL = nil var user, pass string if userInfo := url.User; userInfo != nil { user = userInfo.Username() pass, _ = userInfo.Password() } cinfo := connectInfo{ Verbose: false, Pedantic: false, User: user, Pass: pass, TLS: tlsRequired, Name: c.srv.info.ID, Gateway: c.srv.getGatewayName(), } b, err := json.Marshal(cinfo) if err != nil { panic(err) } c.sendProto([]byte(fmt.Sprintf(ConProto, b)), true) }
[ "func", "(", "c", "*", "client", ")", "sendGatewayConnect", "(", ")", "{", "tlsRequired", ":=", "c", ".", "gw", ".", "cfg", ".", "TLSConfig", "!=", "nil", "\n", "url", ":=", "c", ".", "gw", ".", "connectURL", "\n", "c", ".", "gw", ".", "connectURL", "=", "nil", "\n", "var", "user", ",", "pass", "string", "\n", "if", "userInfo", ":=", "url", ".", "User", ";", "userInfo", "!=", "nil", "{", "user", "=", "userInfo", ".", "Username", "(", ")", "\n", "pass", ",", "_", "=", "userInfo", ".", "Password", "(", ")", "\n", "}", "\n", "cinfo", ":=", "connectInfo", "{", "Verbose", ":", "false", ",", "Pedantic", ":", "false", ",", "User", ":", "user", ",", "Pass", ":", "pass", ",", "TLS", ":", "tlsRequired", ",", "Name", ":", "c", ".", "srv", ".", "info", ".", "ID", ",", "Gateway", ":", "c", ".", "srv", ".", "getGatewayName", "(", ")", ",", "}", "\n", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "cinfo", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "c", ".", "sendProto", "(", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "ConProto", ",", "b", ")", ")", ",", "true", ")", "\n", "}" ]
// Builds and sends the CONNET protocol for a gateway.
[ "Builds", "and", "sends", "the", "CONNET", "protocol", "for", "a", "gateway", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L744-L767
164,178
nats-io/gnatsd
server/gateway.go
gossipGatewaysToInboundGateway
func (s *Server) gossipGatewaysToInboundGateway(gwName string, c *client) { gw := s.gateway gw.RLock() defer gw.RUnlock() for gwCfgName, cfg := range gw.remotes { // Skip the gateway that we just created if gwCfgName == gwName { continue } info := Info{ ID: s.info.ID, GatewayCmd: gatewayCmdGossip, } urls := cfg.getURLsAsStrings() if len(urls) > 0 { info.Gateway = gwCfgName info.GatewayURLs = urls b, _ := json.Marshal(&info) c.mu.Lock() c.sendProto([]byte(fmt.Sprintf(InfoProto, b)), true) c.mu.Unlock() } } }
go
func (s *Server) gossipGatewaysToInboundGateway(gwName string, c *client) { gw := s.gateway gw.RLock() defer gw.RUnlock() for gwCfgName, cfg := range gw.remotes { // Skip the gateway that we just created if gwCfgName == gwName { continue } info := Info{ ID: s.info.ID, GatewayCmd: gatewayCmdGossip, } urls := cfg.getURLsAsStrings() if len(urls) > 0 { info.Gateway = gwCfgName info.GatewayURLs = urls b, _ := json.Marshal(&info) c.mu.Lock() c.sendProto([]byte(fmt.Sprintf(InfoProto, b)), true) c.mu.Unlock() } } }
[ "func", "(", "s", "*", "Server", ")", "gossipGatewaysToInboundGateway", "(", "gwName", "string", ",", "c", "*", "client", ")", "{", "gw", ":=", "s", ".", "gateway", "\n", "gw", ".", "RLock", "(", ")", "\n", "defer", "gw", ".", "RUnlock", "(", ")", "\n", "for", "gwCfgName", ",", "cfg", ":=", "range", "gw", ".", "remotes", "{", "// Skip the gateway that we just created", "if", "gwCfgName", "==", "gwName", "{", "continue", "\n", "}", "\n", "info", ":=", "Info", "{", "ID", ":", "s", ".", "info", ".", "ID", ",", "GatewayCmd", ":", "gatewayCmdGossip", ",", "}", "\n", "urls", ":=", "cfg", ".", "getURLsAsStrings", "(", ")", "\n", "if", "len", "(", "urls", ")", ">", "0", "{", "info", ".", "Gateway", "=", "gwCfgName", "\n", "info", ".", "GatewayURLs", "=", "urls", "\n", "b", ",", "_", ":=", "json", ".", "Marshal", "(", "&", "info", ")", "\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "c", ".", "sendProto", "(", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "InfoProto", ",", "b", ")", ")", ",", "true", ")", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Sends to the given inbound gateway connection a gossip INFO protocol // for each gateway known by this server. This allows for a "full mesh" // of gateways.
[ "Sends", "to", "the", "given", "inbound", "gateway", "connection", "a", "gossip", "INFO", "protocol", "for", "each", "gateway", "known", "by", "this", "server", ".", "This", "allows", "for", "a", "full", "mesh", "of", "gateways", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L948-L971
164,179
nats-io/gnatsd
server/gateway.go
forwardNewGatewayToLocalCluster
func (s *Server) forwardNewGatewayToLocalCluster(oinfo *Info) { // Need to protect s.routes here, so use server's lock s.mu.Lock() defer s.mu.Unlock() // We don't really need the ID to be set, but, we need to make sure // that it is not set to the server ID so that if we were to connect // to an older server that does not expect a "gateway" INFO, it // would think that it needs to create an implicit route (since info.ID // would not match the route's remoteID), but will fail to do so because // the sent protocol will not have host/port defined. info := &Info{ ID: "GW" + s.info.ID, Gateway: oinfo.Gateway, GatewayURLs: oinfo.GatewayURLs, GatewayCmd: gatewayCmdGossip, } b, _ := json.Marshal(info) infoJSON := []byte(fmt.Sprintf(InfoProto, b)) for _, r := range s.routes { r.mu.Lock() r.sendInfo(infoJSON) r.mu.Unlock() } }
go
func (s *Server) forwardNewGatewayToLocalCluster(oinfo *Info) { // Need to protect s.routes here, so use server's lock s.mu.Lock() defer s.mu.Unlock() // We don't really need the ID to be set, but, we need to make sure // that it is not set to the server ID so that if we were to connect // to an older server that does not expect a "gateway" INFO, it // would think that it needs to create an implicit route (since info.ID // would not match the route's remoteID), but will fail to do so because // the sent protocol will not have host/port defined. info := &Info{ ID: "GW" + s.info.ID, Gateway: oinfo.Gateway, GatewayURLs: oinfo.GatewayURLs, GatewayCmd: gatewayCmdGossip, } b, _ := json.Marshal(info) infoJSON := []byte(fmt.Sprintf(InfoProto, b)) for _, r := range s.routes { r.mu.Lock() r.sendInfo(infoJSON) r.mu.Unlock() } }
[ "func", "(", "s", "*", "Server", ")", "forwardNewGatewayToLocalCluster", "(", "oinfo", "*", "Info", ")", "{", "// Need to protect s.routes here, so use server's lock", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// We don't really need the ID to be set, but, we need to make sure", "// that it is not set to the server ID so that if we were to connect", "// to an older server that does not expect a \"gateway\" INFO, it", "// would think that it needs to create an implicit route (since info.ID", "// would not match the route's remoteID), but will fail to do so because", "// the sent protocol will not have host/port defined.", "info", ":=", "&", "Info", "{", "ID", ":", "\"", "\"", "+", "s", ".", "info", ".", "ID", ",", "Gateway", ":", "oinfo", ".", "Gateway", ",", "GatewayURLs", ":", "oinfo", ".", "GatewayURLs", ",", "GatewayCmd", ":", "gatewayCmdGossip", ",", "}", "\n", "b", ",", "_", ":=", "json", ".", "Marshal", "(", "info", ")", "\n", "infoJSON", ":=", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "InfoProto", ",", "b", ")", ")", "\n\n", "for", "_", ",", "r", ":=", "range", "s", ".", "routes", "{", "r", ".", "mu", ".", "Lock", "(", ")", "\n", "r", ".", "sendInfo", "(", "infoJSON", ")", "\n", "r", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}" ]
// Sends the INFO protocol of a gateway to all routes known by this server.
[ "Sends", "the", "INFO", "protocol", "of", "a", "gateway", "to", "all", "routes", "known", "by", "this", "server", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L974-L999
164,180
nats-io/gnatsd
server/gateway.go
sendAccountSubsToGateway
func (s *Server) sendAccountSubsToGateway(c *client, accName []byte) { s.sendSubsToGateway(c, accName) }
go
func (s *Server) sendAccountSubsToGateway(c *client, accName []byte) { s.sendSubsToGateway(c, accName) }
[ "func", "(", "s", "*", "Server", ")", "sendAccountSubsToGateway", "(", "c", "*", "client", ",", "accName", "[", "]", "byte", ")", "{", "s", ".", "sendSubsToGateway", "(", "c", ",", "accName", ")", "\n", "}" ]
// Sends all subscriptions for the given account to the remove gateway // This is sent from the inbound side, that is, the side that receives // messages from the remote's outbound connection. This side is // the one sending the subscription interest.
[ "Sends", "all", "subscriptions", "for", "the", "given", "account", "to", "the", "remove", "gateway", "This", "is", "sent", "from", "the", "inbound", "side", "that", "is", "the", "side", "that", "receives", "messages", "from", "the", "remote", "s", "outbound", "connection", ".", "This", "side", "is", "the", "one", "sending", "the", "subscription", "interest", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1013-L1015
164,181
nats-io/gnatsd
server/gateway.go
sendGatewayConfigsToRoute
func (s *Server) sendGatewayConfigsToRoute(route *client) { gw := s.gateway gw.RLock() // Send only to gateways for which we have actual outbound connection to. if len(gw.out) == 0 { gw.RUnlock() return } // Collect gateway configs for which we have an outbound connection. gwCfgsa := [16]*gatewayCfg{} gwCfgs := gwCfgsa[:0] for _, c := range gw.out { c.mu.Lock() if c.gw.cfg != nil { gwCfgs = append(gwCfgs, c.gw.cfg) } c.mu.Unlock() } gw.RUnlock() if len(gwCfgs) == 0 { return } // Check forwardNewGatewayToLocalCluster() as to why we set ID this way. info := Info{ ID: "GW" + s.info.ID, GatewayCmd: gatewayCmdGossip, } for _, cfg := range gwCfgs { urls := cfg.getURLsAsStrings() if len(urls) > 0 { info.Gateway = cfg.Name info.GatewayURLs = urls b, _ := json.Marshal(&info) route.mu.Lock() route.sendProto([]byte(fmt.Sprintf(InfoProto, b)), true) route.mu.Unlock() } } }
go
func (s *Server) sendGatewayConfigsToRoute(route *client) { gw := s.gateway gw.RLock() // Send only to gateways for which we have actual outbound connection to. if len(gw.out) == 0 { gw.RUnlock() return } // Collect gateway configs for which we have an outbound connection. gwCfgsa := [16]*gatewayCfg{} gwCfgs := gwCfgsa[:0] for _, c := range gw.out { c.mu.Lock() if c.gw.cfg != nil { gwCfgs = append(gwCfgs, c.gw.cfg) } c.mu.Unlock() } gw.RUnlock() if len(gwCfgs) == 0 { return } // Check forwardNewGatewayToLocalCluster() as to why we set ID this way. info := Info{ ID: "GW" + s.info.ID, GatewayCmd: gatewayCmdGossip, } for _, cfg := range gwCfgs { urls := cfg.getURLsAsStrings() if len(urls) > 0 { info.Gateway = cfg.Name info.GatewayURLs = urls b, _ := json.Marshal(&info) route.mu.Lock() route.sendProto([]byte(fmt.Sprintf(InfoProto, b)), true) route.mu.Unlock() } } }
[ "func", "(", "s", "*", "Server", ")", "sendGatewayConfigsToRoute", "(", "route", "*", "client", ")", "{", "gw", ":=", "s", ".", "gateway", "\n", "gw", ".", "RLock", "(", ")", "\n", "// Send only to gateways for which we have actual outbound connection to.", "if", "len", "(", "gw", ".", "out", ")", "==", "0", "{", "gw", ".", "RUnlock", "(", ")", "\n", "return", "\n", "}", "\n", "// Collect gateway configs for which we have an outbound connection.", "gwCfgsa", ":=", "[", "16", "]", "*", "gatewayCfg", "{", "}", "\n", "gwCfgs", ":=", "gwCfgsa", "[", ":", "0", "]", "\n", "for", "_", ",", "c", ":=", "range", "gw", ".", "out", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "c", ".", "gw", ".", "cfg", "!=", "nil", "{", "gwCfgs", "=", "append", "(", "gwCfgs", ",", "c", ".", "gw", ".", "cfg", ")", "\n", "}", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "gw", ".", "RUnlock", "(", ")", "\n", "if", "len", "(", "gwCfgs", ")", "==", "0", "{", "return", "\n", "}", "\n\n", "// Check forwardNewGatewayToLocalCluster() as to why we set ID this way.", "info", ":=", "Info", "{", "ID", ":", "\"", "\"", "+", "s", ".", "info", ".", "ID", ",", "GatewayCmd", ":", "gatewayCmdGossip", ",", "}", "\n", "for", "_", ",", "cfg", ":=", "range", "gwCfgs", "{", "urls", ":=", "cfg", ".", "getURLsAsStrings", "(", ")", "\n", "if", "len", "(", "urls", ")", ">", "0", "{", "info", ".", "Gateway", "=", "cfg", ".", "Name", "\n", "info", ".", "GatewayURLs", "=", "urls", "\n", "b", ",", "_", ":=", "json", ".", "Marshal", "(", "&", "info", ")", "\n", "route", ".", "mu", ".", "Lock", "(", ")", "\n", "route", ".", "sendProto", "(", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "InfoProto", ",", "b", ")", ")", ",", "true", ")", "\n", "route", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Sends INFO protocols to the given route connection for each known Gateway. // These will be processed by the route and delegated to the gateway code to // imvoke processImplicitGateway.
[ "Sends", "INFO", "protocols", "to", "the", "given", "route", "connection", "for", "each", "known", "Gateway", ".", "These", "will", "be", "processed", "by", "the", "route", "and", "delegated", "to", "the", "gateway", "code", "to", "imvoke", "processImplicitGateway", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1135-L1174
164,182
nats-io/gnatsd
server/gateway.go
numOutboundGateways
func (s *Server) numOutboundGateways() int { s.gateway.RLock() n := len(s.gateway.out) s.gateway.RUnlock() return n }
go
func (s *Server) numOutboundGateways() int { s.gateway.RLock() n := len(s.gateway.out) s.gateway.RUnlock() return n }
[ "func", "(", "s", "*", "Server", ")", "numOutboundGateways", "(", ")", "int", "{", "s", ".", "gateway", ".", "RLock", "(", ")", "\n", "n", ":=", "len", "(", "s", ".", "gateway", ".", "out", ")", "\n", "s", ".", "gateway", ".", "RUnlock", "(", ")", "\n", "return", "n", "\n", "}" ]
// Returns the number of outbound gateway connections
[ "Returns", "the", "number", "of", "outbound", "gateway", "connections" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1234-L1239
164,183
nats-io/gnatsd
server/gateway.go
numInboundGateways
func (s *Server) numInboundGateways() int { s.gateway.RLock() n := len(s.gateway.in) s.gateway.RUnlock() return n }
go
func (s *Server) numInboundGateways() int { s.gateway.RLock() n := len(s.gateway.in) s.gateway.RUnlock() return n }
[ "func", "(", "s", "*", "Server", ")", "numInboundGateways", "(", ")", "int", "{", "s", ".", "gateway", ".", "RLock", "(", ")", "\n", "n", ":=", "len", "(", "s", ".", "gateway", ".", "in", ")", "\n", "s", ".", "gateway", ".", "RUnlock", "(", ")", "\n", "return", "n", "\n", "}" ]
// Returns the number of inbound gateway connections
[ "Returns", "the", "number", "of", "inbound", "gateway", "connections" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1242-L1247
164,184
nats-io/gnatsd
server/gateway.go
getConnAttempts
func (g *gatewayCfg) getConnAttempts() int { g.Lock() ca := g.connAttempts g.Unlock() return ca }
go
func (g *gatewayCfg) getConnAttempts() int { g.Lock() ca := g.connAttempts g.Unlock() return ca }
[ "func", "(", "g", "*", "gatewayCfg", ")", "getConnAttempts", "(", ")", "int", "{", "g", ".", "Lock", "(", ")", "\n", "ca", ":=", "g", ".", "connAttempts", "\n", "g", ".", "Unlock", "(", ")", "\n", "return", "ca", "\n", "}" ]
// Used in tests
[ "Used", "in", "tests" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1265-L1270
164,185
nats-io/gnatsd
server/gateway.go
isImplicit
func (g *gatewayCfg) isImplicit() bool { g.RLock() ii := g.implicit g.RUnlock() return ii }
go
func (g *gatewayCfg) isImplicit() bool { g.RLock() ii := g.implicit g.RUnlock() return ii }
[ "func", "(", "g", "*", "gatewayCfg", ")", "isImplicit", "(", ")", "bool", "{", "g", ".", "RLock", "(", ")", "\n", "ii", ":=", "g", ".", "implicit", "\n", "g", ".", "RUnlock", "(", ")", "\n", "return", "ii", "\n", "}" ]
// Returns if this remote gateway is implicit or not.
[ "Returns", "if", "this", "remote", "gateway", "is", "implicit", "or", "not", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1280-L1285
164,186
nats-io/gnatsd
server/gateway.go
getURLs
func (g *gatewayCfg) getURLs() []*url.URL { g.RLock() a := make([]*url.URL, 0, len(g.urls)) for _, u := range g.urls { a = append(a, u) } g.RUnlock() return a }
go
func (g *gatewayCfg) getURLs() []*url.URL { g.RLock() a := make([]*url.URL, 0, len(g.urls)) for _, u := range g.urls { a = append(a, u) } g.RUnlock() return a }
[ "func", "(", "g", "*", "gatewayCfg", ")", "getURLs", "(", ")", "[", "]", "*", "url", ".", "URL", "{", "g", ".", "RLock", "(", ")", "\n", "a", ":=", "make", "(", "[", "]", "*", "url", ".", "URL", ",", "0", ",", "len", "(", "g", ".", "urls", ")", ")", "\n", "for", "_", ",", "u", ":=", "range", "g", ".", "urls", "{", "a", "=", "append", "(", "a", ",", "u", ")", "\n", "}", "\n", "g", ".", "RUnlock", "(", ")", "\n", "return", "a", "\n", "}" ]
// getURLs returns an array of URLs in random order suitable for // an iteration to try to connect.
[ "getURLs", "returns", "an", "array", "of", "URLs", "in", "random", "order", "suitable", "for", "an", "iteration", "to", "try", "to", "connect", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1289-L1297
164,187
nats-io/gnatsd
server/gateway.go
getURLsAsStrings
func (g *gatewayCfg) getURLsAsStrings() []string { g.RLock() a := make([]string, 0, len(g.urls)) for _, u := range g.urls { a = append(a, u.Host) } g.RUnlock() return a }
go
func (g *gatewayCfg) getURLsAsStrings() []string { g.RLock() a := make([]string, 0, len(g.urls)) for _, u := range g.urls { a = append(a, u.Host) } g.RUnlock() return a }
[ "func", "(", "g", "*", "gatewayCfg", ")", "getURLsAsStrings", "(", ")", "[", "]", "string", "{", "g", ".", "RLock", "(", ")", "\n", "a", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "g", ".", "urls", ")", ")", "\n", "for", "_", ",", "u", ":=", "range", "g", ".", "urls", "{", "a", "=", "append", "(", "a", ",", "u", ".", "Host", ")", "\n", "}", "\n", "g", ".", "RUnlock", "(", ")", "\n", "return", "a", "\n", "}" ]
// Similar to getURLs but returns the urls as an array of strings.
[ "Similar", "to", "getURLs", "but", "returns", "the", "urls", "as", "an", "array", "of", "strings", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1300-L1308
164,188
nats-io/gnatsd
server/gateway.go
updateURLs
func (g *gatewayCfg) updateURLs(infoURLs []string) { g.Lock() // Clear the map... g.urls = make(map[string]*url.URL, len(g.URLs)+len(infoURLs)) // Add the urls from the config URLs array. for _, u := range g.URLs { g.urls[u.Host] = u } // Then add the ones from the infoURLs array we got. g.addURLs(infoURLs) g.Unlock() }
go
func (g *gatewayCfg) updateURLs(infoURLs []string) { g.Lock() // Clear the map... g.urls = make(map[string]*url.URL, len(g.URLs)+len(infoURLs)) // Add the urls from the config URLs array. for _, u := range g.URLs { g.urls[u.Host] = u } // Then add the ones from the infoURLs array we got. g.addURLs(infoURLs) g.Unlock() }
[ "func", "(", "g", "*", "gatewayCfg", ")", "updateURLs", "(", "infoURLs", "[", "]", "string", ")", "{", "g", ".", "Lock", "(", ")", "\n", "// Clear the map...", "g", ".", "urls", "=", "make", "(", "map", "[", "string", "]", "*", "url", ".", "URL", ",", "len", "(", "g", ".", "URLs", ")", "+", "len", "(", "infoURLs", ")", ")", "\n", "// Add the urls from the config URLs array.", "for", "_", ",", "u", ":=", "range", "g", ".", "URLs", "{", "g", ".", "urls", "[", "u", ".", "Host", "]", "=", "u", "\n", "}", "\n", "// Then add the ones from the infoURLs array we got.", "g", ".", "addURLs", "(", "infoURLs", ")", "\n", "g", ".", "Unlock", "(", ")", "\n", "}" ]
// updateURLs creates the urls map with the content of the config's URLs array // and the given array that we get from the INFO protocol.
[ "updateURLs", "creates", "the", "urls", "map", "with", "the", "content", "of", "the", "config", "s", "URLs", "array", "and", "the", "given", "array", "that", "we", "get", "from", "the", "INFO", "protocol", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1312-L1323
164,189
nats-io/gnatsd
server/gateway.go
addURLs
func (g *gatewayCfg) addURLs(infoURLs []string) { var scheme string if g.TLSConfig != nil { scheme = "tls" } else { scheme = "nats" } for _, iu := range infoURLs { if _, present := g.urls[iu]; !present { // Urls in Info.GatewayURLs come without scheme. Add it to parse // the url (otherwise it fails). if u, err := url.Parse(fmt.Sprintf("%s://%s", scheme, iu)); err == nil { // Also, if a tlsName has not been set yet and we are dealing // with a hostname and not a bare IP, save the hostname. g.saveTLSHostname(u) // Use u.Host for the key. g.urls[u.Host] = u } } } }
go
func (g *gatewayCfg) addURLs(infoURLs []string) { var scheme string if g.TLSConfig != nil { scheme = "tls" } else { scheme = "nats" } for _, iu := range infoURLs { if _, present := g.urls[iu]; !present { // Urls in Info.GatewayURLs come without scheme. Add it to parse // the url (otherwise it fails). if u, err := url.Parse(fmt.Sprintf("%s://%s", scheme, iu)); err == nil { // Also, if a tlsName has not been set yet and we are dealing // with a hostname and not a bare IP, save the hostname. g.saveTLSHostname(u) // Use u.Host for the key. g.urls[u.Host] = u } } } }
[ "func", "(", "g", "*", "gatewayCfg", ")", "addURLs", "(", "infoURLs", "[", "]", "string", ")", "{", "var", "scheme", "string", "\n", "if", "g", ".", "TLSConfig", "!=", "nil", "{", "scheme", "=", "\"", "\"", "\n", "}", "else", "{", "scheme", "=", "\"", "\"", "\n", "}", "\n", "for", "_", ",", "iu", ":=", "range", "infoURLs", "{", "if", "_", ",", "present", ":=", "g", ".", "urls", "[", "iu", "]", ";", "!", "present", "{", "// Urls in Info.GatewayURLs come without scheme. Add it to parse", "// the url (otherwise it fails).", "if", "u", ",", "err", ":=", "url", ".", "Parse", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "scheme", ",", "iu", ")", ")", ";", "err", "==", "nil", "{", "// Also, if a tlsName has not been set yet and we are dealing", "// with a hostname and not a bare IP, save the hostname.", "g", ".", "saveTLSHostname", "(", "u", ")", "\n", "// Use u.Host for the key.", "g", ".", "urls", "[", "u", ".", "Host", "]", "=", "u", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// add URLs from the given array to the urls map only if not already present. // remoteGateway write lock is assumed to be held on entry. // Write lock is held on entry.
[ "add", "URLs", "from", "the", "given", "array", "to", "the", "urls", "map", "only", "if", "not", "already", "present", ".", "remoteGateway", "write", "lock", "is", "assumed", "to", "be", "held", "on", "entry", ".", "Write", "lock", "is", "held", "on", "entry", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1338-L1358
164,190
nats-io/gnatsd
server/gateway.go
addGatewayURL
func (s *Server) addGatewayURL(urlStr string) { s.gateway.Lock() s.gateway.URLs[urlStr] = struct{}{} s.gateway.Unlock() }
go
func (s *Server) addGatewayURL(urlStr string) { s.gateway.Lock() s.gateway.URLs[urlStr] = struct{}{} s.gateway.Unlock() }
[ "func", "(", "s", "*", "Server", ")", "addGatewayURL", "(", "urlStr", "string", ")", "{", "s", ".", "gateway", ".", "Lock", "(", ")", "\n", "s", ".", "gateway", ".", "URLs", "[", "urlStr", "]", "=", "struct", "{", "}", "{", "}", "\n", "s", ".", "gateway", ".", "Unlock", "(", ")", "\n", "}" ]
// Adds this URL to the set of Gateway URLs // Server lock held on entry
[ "Adds", "this", "URL", "to", "the", "set", "of", "Gateway", "URLs", "Server", "lock", "held", "on", "entry" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1362-L1366
164,191
nats-io/gnatsd
server/gateway.go
removeGatewayURL
func (s *Server) removeGatewayURL(urlStr string) { s.gateway.Lock() delete(s.gateway.URLs, urlStr) s.gateway.Unlock() }
go
func (s *Server) removeGatewayURL(urlStr string) { s.gateway.Lock() delete(s.gateway.URLs, urlStr) s.gateway.Unlock() }
[ "func", "(", "s", "*", "Server", ")", "removeGatewayURL", "(", "urlStr", "string", ")", "{", "s", ".", "gateway", ".", "Lock", "(", ")", "\n", "delete", "(", "s", ".", "gateway", ".", "URLs", ",", "urlStr", ")", "\n", "s", ".", "gateway", ".", "Unlock", "(", ")", "\n", "}" ]
// Remove this URL from the set of gateway URLs // Server lock held on entry
[ "Remove", "this", "URL", "from", "the", "set", "of", "gateway", "URLs", "Server", "lock", "held", "on", "entry" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1370-L1374
164,192
nats-io/gnatsd
server/gateway.go
getGatewayURL
func (s *Server) getGatewayURL() string { s.gateway.RLock() url := s.gateway.URL s.gateway.RUnlock() return url }
go
func (s *Server) getGatewayURL() string { s.gateway.RLock() url := s.gateway.URL s.gateway.RUnlock() return url }
[ "func", "(", "s", "*", "Server", ")", "getGatewayURL", "(", ")", "string", "{", "s", ".", "gateway", ".", "RLock", "(", ")", "\n", "url", ":=", "s", ".", "gateway", ".", "URL", "\n", "s", ".", "gateway", ".", "RUnlock", "(", ")", "\n", "return", "url", "\n", "}" ]
// This returns the URL of the Gateway listen spec, or empty string // if the server has no gateway configured.
[ "This", "returns", "the", "URL", "of", "the", "Gateway", "listen", "spec", "or", "empty", "string", "if", "the", "server", "has", "no", "gateway", "configured", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1378-L1383
164,193
nats-io/gnatsd
server/gateway.go
getOutboundGatewayConnections
func (s *Server) getOutboundGatewayConnections(a *[]*client) { s.gateway.RLock() for i := 0; i < len(s.gateway.outo); i++ { *a = append(*a, s.gateway.outo[i]) } s.gateway.RUnlock() }
go
func (s *Server) getOutboundGatewayConnections(a *[]*client) { s.gateway.RLock() for i := 0; i < len(s.gateway.outo); i++ { *a = append(*a, s.gateway.outo[i]) } s.gateway.RUnlock() }
[ "func", "(", "s", "*", "Server", ")", "getOutboundGatewayConnections", "(", "a", "*", "[", "]", "*", "client", ")", "{", "s", ".", "gateway", ".", "RLock", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ".", "gateway", ".", "outo", ")", ";", "i", "++", "{", "*", "a", "=", "append", "(", "*", "a", ",", "s", ".", "gateway", ".", "outo", "[", "i", "]", ")", "\n", "}", "\n", "s", ".", "gateway", ".", "RUnlock", "(", ")", "\n", "}" ]
// Returns all outbound gateway connections in the provided array. // The order of the gateways is suited for the sending of a message. // Current ordering is based on individual gateway's RTT value.
[ "Returns", "all", "outbound", "gateway", "connections", "in", "the", "provided", "array", ".", "The", "order", "of", "the", "gateways", "is", "suited", "for", "the", "sending", "of", "a", "message", ".", "Current", "ordering", "is", "based", "on", "individual", "gateway", "s", "RTT", "value", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1437-L1443
164,194
nats-io/gnatsd
server/gateway.go
orderOutboundConnectionsLocked
func (g *srvGateway) orderOutboundConnectionsLocked() { // Order the gateways by lowest RTT sort.Slice(g.outo, func(i, j int) bool { return g.outo[i].getRTTValue() < g.outo[j].getRTTValue() }) }
go
func (g *srvGateway) orderOutboundConnectionsLocked() { // Order the gateways by lowest RTT sort.Slice(g.outo, func(i, j int) bool { return g.outo[i].getRTTValue() < g.outo[j].getRTTValue() }) }
[ "func", "(", "g", "*", "srvGateway", ")", "orderOutboundConnectionsLocked", "(", ")", "{", "// Order the gateways by lowest RTT", "sort", ".", "Slice", "(", "g", ".", "outo", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "g", ".", "outo", "[", "i", "]", ".", "getRTTValue", "(", ")", "<", "g", ".", "outo", "[", "j", "]", ".", "getRTTValue", "(", ")", "\n", "}", ")", "\n", "}" ]
// Orders the array of outbound connections. // Current ordering is by lowest RTT. // Gateway write lock is held on entry
[ "Orders", "the", "array", "of", "outbound", "connections", ".", "Current", "ordering", "is", "by", "lowest", "RTT", ".", "Gateway", "write", "lock", "is", "held", "on", "entry" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1448-L1453
164,195
nats-io/gnatsd
server/gateway.go
getInboundGatewayConnections
func (s *Server) getInboundGatewayConnections(a *[]*client) { s.gateway.RLock() for _, gwc := range s.gateway.in { *a = append(*a, gwc) } s.gateway.RUnlock() }
go
func (s *Server) getInboundGatewayConnections(a *[]*client) { s.gateway.RLock() for _, gwc := range s.gateway.in { *a = append(*a, gwc) } s.gateway.RUnlock() }
[ "func", "(", "s", "*", "Server", ")", "getInboundGatewayConnections", "(", "a", "*", "[", "]", "*", "client", ")", "{", "s", ".", "gateway", ".", "RLock", "(", ")", "\n", "for", "_", ",", "gwc", ":=", "range", "s", ".", "gateway", ".", "in", "{", "*", "a", "=", "append", "(", "*", "a", ",", "gwc", ")", "\n", "}", "\n", "s", ".", "gateway", ".", "RUnlock", "(", ")", "\n", "}" ]
// Returns all inbound gateway connections in the provided array
[ "Returns", "all", "inbound", "gateway", "connections", "in", "the", "provided", "array" ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1464-L1470
164,196
nats-io/gnatsd
server/gateway.go
removeRemoteGatewayConnection
func (s *Server) removeRemoteGatewayConnection(c *client) { c.mu.Lock() cid := c.cid isOutbound := c.gw.outbound gwName := c.gw.name c.mu.Unlock() gw := s.gateway gw.Lock() if isOutbound { delete(gw.out, gwName) louto := len(gw.outo) reorder := false for i := 0; i < len(gw.outo); i++ { if gw.outo[i] == c { // If last, simply remove and no need to reorder if i != louto-1 { gw.outo[i] = gw.outo[louto-1] reorder = true } gw.outo = gw.outo[:louto-1] } } if reorder { gw.orderOutboundConnectionsLocked() } } else { delete(gw.in, cid) } gw.Unlock() s.removeFromTempClients(cid) if isOutbound { // Update number of totalQSubs for this gateway qSubsRemoved := int64(0) c.mu.Lock() for _, sub := range c.subs { if sub.queue != nil { qSubsRemoved++ } } c.mu.Unlock() // Update total count of qsubs in remote gateways. atomic.AddInt64(&c.srv.gateway.totalQSubs, -qSubsRemoved) } else { var subsa [1024]*subscription var subs = subsa[:0] // For inbound GW connection, if we have subs, those are // local subs on "_R_." subjects. c.mu.Lock() for _, sub := range c.subs { subs = append(subs, sub) } c.mu.Unlock() for _, sub := range subs { c.removeReplySub(sub) } } }
go
func (s *Server) removeRemoteGatewayConnection(c *client) { c.mu.Lock() cid := c.cid isOutbound := c.gw.outbound gwName := c.gw.name c.mu.Unlock() gw := s.gateway gw.Lock() if isOutbound { delete(gw.out, gwName) louto := len(gw.outo) reorder := false for i := 0; i < len(gw.outo); i++ { if gw.outo[i] == c { // If last, simply remove and no need to reorder if i != louto-1 { gw.outo[i] = gw.outo[louto-1] reorder = true } gw.outo = gw.outo[:louto-1] } } if reorder { gw.orderOutboundConnectionsLocked() } } else { delete(gw.in, cid) } gw.Unlock() s.removeFromTempClients(cid) if isOutbound { // Update number of totalQSubs for this gateway qSubsRemoved := int64(0) c.mu.Lock() for _, sub := range c.subs { if sub.queue != nil { qSubsRemoved++ } } c.mu.Unlock() // Update total count of qsubs in remote gateways. atomic.AddInt64(&c.srv.gateway.totalQSubs, -qSubsRemoved) } else { var subsa [1024]*subscription var subs = subsa[:0] // For inbound GW connection, if we have subs, those are // local subs on "_R_." subjects. c.mu.Lock() for _, sub := range c.subs { subs = append(subs, sub) } c.mu.Unlock() for _, sub := range subs { c.removeReplySub(sub) } } }
[ "func", "(", "s", "*", "Server", ")", "removeRemoteGatewayConnection", "(", "c", "*", "client", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "cid", ":=", "c", ".", "cid", "\n", "isOutbound", ":=", "c", ".", "gw", ".", "outbound", "\n", "gwName", ":=", "c", ".", "gw", ".", "name", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "gw", ":=", "s", ".", "gateway", "\n", "gw", ".", "Lock", "(", ")", "\n", "if", "isOutbound", "{", "delete", "(", "gw", ".", "out", ",", "gwName", ")", "\n", "louto", ":=", "len", "(", "gw", ".", "outo", ")", "\n", "reorder", ":=", "false", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "gw", ".", "outo", ")", ";", "i", "++", "{", "if", "gw", ".", "outo", "[", "i", "]", "==", "c", "{", "// If last, simply remove and no need to reorder", "if", "i", "!=", "louto", "-", "1", "{", "gw", ".", "outo", "[", "i", "]", "=", "gw", ".", "outo", "[", "louto", "-", "1", "]", "\n", "reorder", "=", "true", "\n", "}", "\n", "gw", ".", "outo", "=", "gw", ".", "outo", "[", ":", "louto", "-", "1", "]", "\n", "}", "\n", "}", "\n", "if", "reorder", "{", "gw", ".", "orderOutboundConnectionsLocked", "(", ")", "\n", "}", "\n", "}", "else", "{", "delete", "(", "gw", ".", "in", ",", "cid", ")", "\n", "}", "\n", "gw", ".", "Unlock", "(", ")", "\n", "s", ".", "removeFromTempClients", "(", "cid", ")", "\n\n", "if", "isOutbound", "{", "// Update number of totalQSubs for this gateway", "qSubsRemoved", ":=", "int64", "(", "0", ")", "\n", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "sub", ":=", "range", "c", ".", "subs", "{", "if", "sub", ".", "queue", "!=", "nil", "{", "qSubsRemoved", "++", "\n", "}", "\n", "}", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "// Update total count of qsubs in remote gateways.", "atomic", ".", "AddInt64", "(", "&", "c", ".", "srv", ".", "gateway", ".", "totalQSubs", ",", "-", "qSubsRemoved", ")", "\n\n", "}", "else", "{", "var", "subsa", "[", "1024", "]", "*", "subscription", "\n", "var", "subs", "=", "subsa", "[", ":", "0", "]", "\n\n", "// For inbound GW connection, if we have subs, those are", "// local subs on \"_R_.\" subjects.", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "for", "_", ",", "sub", ":=", "range", "c", ".", "subs", "{", "subs", "=", "append", "(", "subs", ",", "sub", ")", "\n", "}", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "sub", ":=", "range", "subs", "{", "c", ".", "removeReplySub", "(", "sub", ")", "\n", "}", "\n", "}", "\n", "}" ]
// This is invoked when a gateway connection is closed and the server // is removing this connection from its state.
[ "This", "is", "invoked", "when", "a", "gateway", "connection", "is", "closed", "and", "the", "server", "is", "removing", "this", "connection", "from", "its", "state", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1474-L1534
164,197
nats-io/gnatsd
server/gateway.go
GatewayAddr
func (s *Server) GatewayAddr() *net.TCPAddr { s.mu.Lock() defer s.mu.Unlock() if s.gatewayListener == nil { return nil } return s.gatewayListener.Addr().(*net.TCPAddr) }
go
func (s *Server) GatewayAddr() *net.TCPAddr { s.mu.Lock() defer s.mu.Unlock() if s.gatewayListener == nil { return nil } return s.gatewayListener.Addr().(*net.TCPAddr) }
[ "func", "(", "s", "*", "Server", ")", "GatewayAddr", "(", ")", "*", "net", ".", "TCPAddr", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "gatewayListener", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "s", ".", "gatewayListener", ".", "Addr", "(", ")", ".", "(", "*", "net", ".", "TCPAddr", ")", "\n", "}" ]
// GatewayAddr returns the net.Addr object for the gateway listener.
[ "GatewayAddr", "returns", "the", "net", ".", "Addr", "object", "for", "the", "gateway", "listener", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1537-L1544
164,198
nats-io/gnatsd
server/gateway.go
switchAccountToInterestMode
func (s *Server) switchAccountToInterestMode(accName string) { gwsa := [16]*client{} gws := gwsa[:0] s.getInboundGatewayConnections(&gws) for _, gin := range gws { var e *insie var ok bool gin.mu.Lock() if e, ok = gin.gw.insim[accName]; !ok || e == nil { e = &insie{} gin.gw.insim[accName] = e } gin.gatewaySwitchAccountToSendAllSubs(e, []byte(accName)) gin.mu.Unlock() } }
go
func (s *Server) switchAccountToInterestMode(accName string) { gwsa := [16]*client{} gws := gwsa[:0] s.getInboundGatewayConnections(&gws) for _, gin := range gws { var e *insie var ok bool gin.mu.Lock() if e, ok = gin.gw.insim[accName]; !ok || e == nil { e = &insie{} gin.gw.insim[accName] = e } gin.gatewaySwitchAccountToSendAllSubs(e, []byte(accName)) gin.mu.Unlock() } }
[ "func", "(", "s", "*", "Server", ")", "switchAccountToInterestMode", "(", "accName", "string", ")", "{", "gwsa", ":=", "[", "16", "]", "*", "client", "{", "}", "\n", "gws", ":=", "gwsa", "[", ":", "0", "]", "\n", "s", ".", "getInboundGatewayConnections", "(", "&", "gws", ")", "\n\n", "for", "_", ",", "gin", ":=", "range", "gws", "{", "var", "e", "*", "insie", "\n", "var", "ok", "bool", "\n\n", "gin", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "e", ",", "ok", "=", "gin", ".", "gw", ".", "insim", "[", "accName", "]", ";", "!", "ok", "||", "e", "==", "nil", "{", "e", "=", "&", "insie", "{", "}", "\n", "gin", ".", "gw", ".", "insim", "[", "accName", "]", "=", "e", "\n", "}", "\n", "gin", ".", "gatewaySwitchAccountToSendAllSubs", "(", "e", ",", "[", "]", "byte", "(", "accName", ")", ")", "\n", "gin", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "}" ]
// switchAccountToInterestMode will switch an account over to interestMode. // Lock should NOT be held.
[ "switchAccountToInterestMode", "will", "switch", "an", "account", "over", "to", "interestMode", ".", "Lock", "should", "NOT", "be", "held", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L1824-L1841
164,199
nats-io/gnatsd
server/gateway.go
gatewayHandleAccountNoInterest
func (s *Server) gatewayHandleAccountNoInterest(c *client, accName []byte) { // Check and possibly send the A- under this lock. s.gateway.pasi.Lock() defer s.gateway.pasi.Unlock() si, inMap := s.gateway.pasi.m[string(accName)] if inMap && si != nil && len(si) > 0 { return } c.sendAccountUnsubToGateway(accName) }
go
func (s *Server) gatewayHandleAccountNoInterest(c *client, accName []byte) { // Check and possibly send the A- under this lock. s.gateway.pasi.Lock() defer s.gateway.pasi.Unlock() si, inMap := s.gateway.pasi.m[string(accName)] if inMap && si != nil && len(si) > 0 { return } c.sendAccountUnsubToGateway(accName) }
[ "func", "(", "s", "*", "Server", ")", "gatewayHandleAccountNoInterest", "(", "c", "*", "client", ",", "accName", "[", "]", "byte", ")", "{", "// Check and possibly send the A- under this lock.", "s", ".", "gateway", ".", "pasi", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "gateway", ".", "pasi", ".", "Unlock", "(", ")", "\n\n", "si", ",", "inMap", ":=", "s", ".", "gateway", ".", "pasi", ".", "m", "[", "string", "(", "accName", ")", "]", "\n", "if", "inMap", "&&", "si", "!=", "nil", "&&", "len", "(", "si", ")", ">", "0", "{", "return", "\n", "}", "\n", "c", ".", "sendAccountUnsubToGateway", "(", "accName", ")", "\n", "}" ]
// Possibly sends an A- to the remote gateway `c`. // Invoked when processing an inbound message and the account is not found. // A check under a lock that protects processing of SUBs and UNSUBs is // done to make sure that we don't send the A- if a subscription has just // been created at the same time, which would otherwise results in the // remote never sending messages on this account until a new subscription // is created.
[ "Possibly", "sends", "an", "A", "-", "to", "the", "remote", "gateway", "c", ".", "Invoked", "when", "processing", "an", "inbound", "message", "and", "the", "account", "is", "not", "found", ".", "A", "check", "under", "a", "lock", "that", "protects", "processing", "of", "SUBs", "and", "UNSUBs", "is", "done", "to", "make", "sure", "that", "we", "don", "t", "send", "the", "A", "-", "if", "a", "subscription", "has", "just", "been", "created", "at", "the", "same", "time", "which", "would", "otherwise", "results", "in", "the", "remote", "never", "sending", "messages", "on", "this", "account", "until", "a", "new", "subscription", "is", "created", "." ]
7ebe2836016a033f11d9da712ed6a1abb95c06dd
https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L2277-L2287