id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens listlengths 21 1.41k | docstring stringlengths 6 2.61k | docstring_tokens listlengths 3 215 | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
164,200 | nats-io/gnatsd | server/gateway.go | sendAccountUnsubToGateway | func (c *client) sendAccountUnsubToGateway(accName []byte) {
// Check if we have sent the A- or not.
c.mu.Lock()
e, sent := c.gw.insim[string(accName)]
if e != nil || !sent {
// Add a nil value to indicate that we have sent an A-
// so that we know to send A+ when needed.
c.gw.insim[string(accName)] = nil
var protoa [256]byte
proto := protoa[:0]
proto = append(proto, aUnsubBytes...)
proto = append(proto, accName...)
proto = append(proto, CR_LF...)
c.sendProto(proto, false)
if c.trace {
c.traceOutOp("", proto[:len(proto)-LEN_CR_LF])
}
}
c.mu.Unlock()
} | go | func (c *client) sendAccountUnsubToGateway(accName []byte) {
// Check if we have sent the A- or not.
c.mu.Lock()
e, sent := c.gw.insim[string(accName)]
if e != nil || !sent {
// Add a nil value to indicate that we have sent an A-
// so that we know to send A+ when needed.
c.gw.insim[string(accName)] = nil
var protoa [256]byte
proto := protoa[:0]
proto = append(proto, aUnsubBytes...)
proto = append(proto, accName...)
proto = append(proto, CR_LF...)
c.sendProto(proto, false)
if c.trace {
c.traceOutOp("", proto[:len(proto)-LEN_CR_LF])
}
}
c.mu.Unlock()
} | [
"func",
"(",
"c",
"*",
"client",
")",
"sendAccountUnsubToGateway",
"(",
"accName",
"[",
"]",
"byte",
")",
"{",
"// Check if we have sent the A- or not.",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"e",
",",
"sent",
":=",
"c",
".",
"gw",
".",
"insim",
... | // Helper that sends an A- to this remote gateway if not already done.
// This function should not be invoked directly but instead be invoked
// by functions holding the gateway.pasi's Lock. | [
"Helper",
"that",
"sends",
"an",
"A",
"-",
"to",
"this",
"remote",
"gateway",
"if",
"not",
"already",
"done",
".",
"This",
"function",
"should",
"not",
"be",
"invoked",
"directly",
"but",
"instead",
"be",
"invoked",
"by",
"functions",
"holding",
"the",
"ga... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L2292-L2311 |
164,201 | nats-io/gnatsd | server/gateway.go | getAccountFromGatewayCommand | func getAccountFromGatewayCommand(c *client, info *Info, cmd string) string {
if info.GatewayCmdPayload == nil {
c.sendErrAndErr(fmt.Sprintf("Account absent from receive-all-subscriptions-%s command", cmd))
c.closeConnection(ProtocolViolation)
return ""
}
return string(info.GatewayCmdPayload)
} | go | func getAccountFromGatewayCommand(c *client, info *Info, cmd string) string {
if info.GatewayCmdPayload == nil {
c.sendErrAndErr(fmt.Sprintf("Account absent from receive-all-subscriptions-%s command", cmd))
c.closeConnection(ProtocolViolation)
return ""
}
return string(info.GatewayCmdPayload)
} | [
"func",
"getAccountFromGatewayCommand",
"(",
"c",
"*",
"client",
",",
"info",
"*",
"Info",
",",
"cmd",
"string",
")",
"string",
"{",
"if",
"info",
".",
"GatewayCmdPayload",
"==",
"nil",
"{",
"c",
".",
"sendErrAndErr",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"... | // small helper to get the account name from the INFO command. | [
"small",
"helper",
"to",
"get",
"the",
"account",
"name",
"from",
"the",
"INFO",
"command",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/gateway.go#L2529-L2536 |
164,202 | nats-io/gnatsd | logger/log.go | NewStdLogger | func NewStdLogger(time, debug, trace, colors, pid bool) *Logger {
flags := 0
if time {
flags = log.LstdFlags | log.Lmicroseconds
}
pre := ""
if pid {
pre = pidPrefix()
}
l := &Logger{
logger: log.New(os.Stderr, pre, flags),
debug: debug,
trace: trace,
}
if colors {
setColoredLabelFormats(l)
} else {
setPlainLabelFormats(l)
}
return l
} | go | func NewStdLogger(time, debug, trace, colors, pid bool) *Logger {
flags := 0
if time {
flags = log.LstdFlags | log.Lmicroseconds
}
pre := ""
if pid {
pre = pidPrefix()
}
l := &Logger{
logger: log.New(os.Stderr, pre, flags),
debug: debug,
trace: trace,
}
if colors {
setColoredLabelFormats(l)
} else {
setPlainLabelFormats(l)
}
return l
} | [
"func",
"NewStdLogger",
"(",
"time",
",",
"debug",
",",
"trace",
",",
"colors",
",",
"pid",
"bool",
")",
"*",
"Logger",
"{",
"flags",
":=",
"0",
"\n",
"if",
"time",
"{",
"flags",
"=",
"log",
".",
"LstdFlags",
"|",
"log",
".",
"Lmicroseconds",
"\n",
... | // NewStdLogger creates a logger with output directed to Stderr | [
"NewStdLogger",
"creates",
"a",
"logger",
"with",
"output",
"directed",
"to",
"Stderr"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/logger/log.go#L38-L62 |
164,203 | nats-io/gnatsd | logger/log.go | NewFileLogger | func NewFileLogger(filename string, time, debug, trace, pid bool) *Logger {
fileflags := os.O_WRONLY | os.O_APPEND | os.O_CREATE
f, err := os.OpenFile(filename, fileflags, 0660)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
flags := 0
if time {
flags = log.LstdFlags | log.Lmicroseconds
}
pre := ""
if pid {
pre = pidPrefix()
}
l := &Logger{
logger: log.New(f, pre, flags),
debug: debug,
trace: trace,
logFile: f,
}
setPlainLabelFormats(l)
return l
} | go | func NewFileLogger(filename string, time, debug, trace, pid bool) *Logger {
fileflags := os.O_WRONLY | os.O_APPEND | os.O_CREATE
f, err := os.OpenFile(filename, fileflags, 0660)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
flags := 0
if time {
flags = log.LstdFlags | log.Lmicroseconds
}
pre := ""
if pid {
pre = pidPrefix()
}
l := &Logger{
logger: log.New(f, pre, flags),
debug: debug,
trace: trace,
logFile: f,
}
setPlainLabelFormats(l)
return l
} | [
"func",
"NewFileLogger",
"(",
"filename",
"string",
",",
"time",
",",
"debug",
",",
"trace",
",",
"pid",
"bool",
")",
"*",
"Logger",
"{",
"fileflags",
":=",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_APPEND",
"|",
"os",
".",
"O_CREATE",
"\n",
"f",
","... | // NewFileLogger creates a logger with output directed to a file | [
"NewFileLogger",
"creates",
"a",
"logger",
"with",
"output",
"directed",
"to",
"a",
"file"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/logger/log.go#L65-L91 |
164,204 | nats-io/gnatsd | logger/log.go | Close | func (l *Logger) Close() error {
if f := l.logFile; f != nil {
l.logFile = nil
return f.Close()
}
return nil
} | go | func (l *Logger) Close() error {
if f := l.logFile; f != nil {
l.logFile = nil
return f.Close()
}
return nil
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"f",
":=",
"l",
".",
"logFile",
";",
"f",
"!=",
"nil",
"{",
"l",
".",
"logFile",
"=",
"nil",
"\n",
"return",
"f",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
... | // Close implements the io.Closer interface to clean up
// resources in the server's logger implementation.
// Caller must ensure threadsafety. | [
"Close",
"implements",
"the",
"io",
".",
"Closer",
"interface",
"to",
"clean",
"up",
"resources",
"in",
"the",
"server",
"s",
"logger",
"implementation",
".",
"Caller",
"must",
"ensure",
"threadsafety",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/logger/log.go#L112-L118 |
164,205 | nats-io/gnatsd | logger/log.go | Warnf | func (l *Logger) Warnf(format string, v ...interface{}) {
l.logger.Printf(l.warnLabel+format, v...)
} | go | func (l *Logger) Warnf(format string, v ...interface{}) {
l.logger.Printf(l.warnLabel+format, v...)
} | [
"func",
"(",
"l",
"*",
"Logger",
")",
"Warnf",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"logger",
".",
"Printf",
"(",
"l",
".",
"warnLabel",
"+",
"format",
",",
"v",
"...",
")",
"\n",
"}"
] | // Warnf logs a notice statement | [
"Warnf",
"logs",
"a",
"notice",
"statement"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/logger/log.go#L150-L152 |
164,206 | nats-io/gnatsd | server/route.go | addReplySubTimeout | func (c *client) addReplySubTimeout(acc *Account, sub *subscription, d time.Duration) {
if c.route.replySubs == nil {
c.route.replySubs = make(map[*subscription]*time.Timer)
}
rs := c.route.replySubs
rs[sub] = time.AfterFunc(d, func() {
c.mu.Lock()
delete(rs, sub)
sub.max = 0
c.mu.Unlock()
c.unsubscribe(acc, sub, true)
})
} | go | func (c *client) addReplySubTimeout(acc *Account, sub *subscription, d time.Duration) {
if c.route.replySubs == nil {
c.route.replySubs = make(map[*subscription]*time.Timer)
}
rs := c.route.replySubs
rs[sub] = time.AfterFunc(d, func() {
c.mu.Lock()
delete(rs, sub)
sub.max = 0
c.mu.Unlock()
c.unsubscribe(acc, sub, true)
})
} | [
"func",
"(",
"c",
"*",
"client",
")",
"addReplySubTimeout",
"(",
"acc",
"*",
"Account",
",",
"sub",
"*",
"subscription",
",",
"d",
"time",
".",
"Duration",
")",
"{",
"if",
"c",
".",
"route",
".",
"replySubs",
"==",
"nil",
"{",
"c",
".",
"route",
".... | // This will add a timer to watch over remote reply subjects in case
// they fail to receive a response. The duration will be taken from the
// accounts map timeout to match.
// Lock should be held upon entering. | [
"This",
"will",
"add",
"a",
"timer",
"to",
"watch",
"over",
"remote",
"reply",
"subjects",
"in",
"case",
"they",
"fail",
"to",
"receive",
"a",
"response",
".",
"The",
"duration",
"will",
"be",
"taken",
"from",
"the",
"accounts",
"map",
"timeout",
"to",
"... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L106-L118 |
164,207 | nats-io/gnatsd | server/route.go | removeReplySub | func (c *client) removeReplySub(sub *subscription) {
if sub == nil {
return
}
// Lookup the account based on sub.sid.
if i := bytes.Index(sub.sid, []byte(" ")); i > 0 {
// First part of SID for route is account name.
if acc, _ := c.srv.LookupAccount(string(sub.sid[:i])); acc != nil {
acc.sl.Remove(sub)
}
c.mu.Lock()
c.removeReplySubTimeout(sub)
delete(c.subs, string(sub.sid))
c.mu.Unlock()
}
} | go | func (c *client) removeReplySub(sub *subscription) {
if sub == nil {
return
}
// Lookup the account based on sub.sid.
if i := bytes.Index(sub.sid, []byte(" ")); i > 0 {
// First part of SID for route is account name.
if acc, _ := c.srv.LookupAccount(string(sub.sid[:i])); acc != nil {
acc.sl.Remove(sub)
}
c.mu.Lock()
c.removeReplySubTimeout(sub)
delete(c.subs, string(sub.sid))
c.mu.Unlock()
}
} | [
"func",
"(",
"c",
"*",
"client",
")",
"removeReplySub",
"(",
"sub",
"*",
"subscription",
")",
"{",
"if",
"sub",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// Lookup the account based on sub.sid.",
"if",
"i",
":=",
"bytes",
".",
"Index",
"(",
"sub",
".... | // removeReplySub is called when we trip the max on remoteReply subs. | [
"removeReplySub",
"is",
"called",
"when",
"we",
"trip",
"the",
"max",
"on",
"remoteReply",
"subs",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L121-L136 |
164,208 | nats-io/gnatsd | server/route.go | removeReplySubTimeout | func (c *client) removeReplySubTimeout(sub *subscription) {
// Remove any reply sub timer if it exists.
if c.route == nil || c.route.replySubs == nil {
return
}
if t, ok := c.route.replySubs[sub]; ok {
t.Stop()
delete(c.route.replySubs, sub)
}
} | go | func (c *client) removeReplySubTimeout(sub *subscription) {
// Remove any reply sub timer if it exists.
if c.route == nil || c.route.replySubs == nil {
return
}
if t, ok := c.route.replySubs[sub]; ok {
t.Stop()
delete(c.route.replySubs, sub)
}
} | [
"func",
"(",
"c",
"*",
"client",
")",
"removeReplySubTimeout",
"(",
"sub",
"*",
"subscription",
")",
"{",
"// Remove any reply sub timer if it exists.",
"if",
"c",
".",
"route",
"==",
"nil",
"||",
"c",
".",
"route",
".",
"replySubs",
"==",
"nil",
"{",
"retur... | // removeReplySubTimeout will remove a timer if it exists.
// Lock should be held upon entering. | [
"removeReplySubTimeout",
"will",
"remove",
"a",
"timer",
"if",
"it",
"exists",
".",
"Lock",
"should",
"be",
"held",
"upon",
"entering",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L140-L149 |
164,209 | nats-io/gnatsd | server/route.go | processInboundRoutedMsg | func (c *client) processInboundRoutedMsg(msg []byte) {
// Update statistics
c.in.msgs++
// The msg includes the CR_LF, so pull back out for accounting.
c.in.bytes += int32(len(msg) - LEN_CR_LF)
if c.trace {
c.traceMsg(msg)
}
if c.opts.Verbose {
c.sendOK()
}
// Mostly under testing scenarios.
if c.srv == nil {
return
}
acc, r := c.getAccAndResultFromCache()
if acc == nil {
c.Debugf("Unknown account %q for routed message on subject: %q", c.pa.account, c.pa.subject)
return
}
// Check to see if we need to map/route to another account.
if acc.imports.services != nil {
c.checkForImportServices(acc, msg)
}
// Check for no interest, short circuit if so.
// This is the fanout scale.
if len(r.psubs)+len(r.qsubs) == 0 {
return
}
// Check to see if we have a routed message with a service reply.
if isServiceReply(c.pa.reply) && acc != nil {
// Need to add a sub here for local interest to send a response back
// to the originating server/requestor where it will be re-mapped.
sid := make([]byte, 0, len(acc.Name)+len(c.pa.reply)+1)
sid = append(sid, acc.Name...)
sid = append(sid, ' ')
sid = append(sid, c.pa.reply...)
// Copy off the reply since otherwise we are referencing a buffer that will be reused.
reply := make([]byte, len(c.pa.reply))
copy(reply, c.pa.reply)
sub := &subscription{client: c, subject: reply, sid: sid, max: 1}
if err := acc.sl.Insert(sub); err != nil {
c.Errorf("Could not insert subscription: %v", err)
} else {
ttl := acc.AutoExpireTTL()
c.mu.Lock()
c.subs[string(sid)] = sub
c.addReplySubTimeout(acc, sub, ttl)
c.mu.Unlock()
}
}
c.processMsgResults(acc, r, msg, c.pa.subject, c.pa.reply, pmrNoFlag)
} | go | func (c *client) processInboundRoutedMsg(msg []byte) {
// Update statistics
c.in.msgs++
// The msg includes the CR_LF, so pull back out for accounting.
c.in.bytes += int32(len(msg) - LEN_CR_LF)
if c.trace {
c.traceMsg(msg)
}
if c.opts.Verbose {
c.sendOK()
}
// Mostly under testing scenarios.
if c.srv == nil {
return
}
acc, r := c.getAccAndResultFromCache()
if acc == nil {
c.Debugf("Unknown account %q for routed message on subject: %q", c.pa.account, c.pa.subject)
return
}
// Check to see if we need to map/route to another account.
if acc.imports.services != nil {
c.checkForImportServices(acc, msg)
}
// Check for no interest, short circuit if so.
// This is the fanout scale.
if len(r.psubs)+len(r.qsubs) == 0 {
return
}
// Check to see if we have a routed message with a service reply.
if isServiceReply(c.pa.reply) && acc != nil {
// Need to add a sub here for local interest to send a response back
// to the originating server/requestor where it will be re-mapped.
sid := make([]byte, 0, len(acc.Name)+len(c.pa.reply)+1)
sid = append(sid, acc.Name...)
sid = append(sid, ' ')
sid = append(sid, c.pa.reply...)
// Copy off the reply since otherwise we are referencing a buffer that will be reused.
reply := make([]byte, len(c.pa.reply))
copy(reply, c.pa.reply)
sub := &subscription{client: c, subject: reply, sid: sid, max: 1}
if err := acc.sl.Insert(sub); err != nil {
c.Errorf("Could not insert subscription: %v", err)
} else {
ttl := acc.AutoExpireTTL()
c.mu.Lock()
c.subs[string(sid)] = sub
c.addReplySubTimeout(acc, sub, ttl)
c.mu.Unlock()
}
}
c.processMsgResults(acc, r, msg, c.pa.subject, c.pa.reply, pmrNoFlag)
} | [
"func",
"(",
"c",
"*",
"client",
")",
"processInboundRoutedMsg",
"(",
"msg",
"[",
"]",
"byte",
")",
"{",
"// Update statistics",
"c",
".",
"in",
".",
"msgs",
"++",
"\n",
"// The msg includes the CR_LF, so pull back out for accounting.",
"c",
".",
"in",
".",
"byt... | // processInboundRouteMsg is called to process an inbound msg from a route. | [
"processInboundRouteMsg",
"is",
"called",
"to",
"process",
"an",
"inbound",
"msg",
"from",
"a",
"route",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L244-L303 |
164,210 | nats-io/gnatsd | server/route.go | makeQFilter | func (c *client) makeQFilter(qsubs [][]*subscription) {
qs := make([][]byte, 0, len(qsubs))
for _, qsub := range qsubs {
if len(qsub) > 0 {
qs = append(qs, qsub[0].queue)
}
}
c.pa.queues = qs
} | go | func (c *client) makeQFilter(qsubs [][]*subscription) {
qs := make([][]byte, 0, len(qsubs))
for _, qsub := range qsubs {
if len(qsub) > 0 {
qs = append(qs, qsub[0].queue)
}
}
c.pa.queues = qs
} | [
"func",
"(",
"c",
"*",
"client",
")",
"makeQFilter",
"(",
"qsubs",
"[",
"]",
"[",
"]",
"*",
"subscription",
")",
"{",
"qs",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"0",
",",
"len",
"(",
"qsubs",
")",
")",
"\n",
"for",
"_",
",",
... | // Helper function for routes and gateways to create qfilters need for
// converted subs from imports, etc. | [
"Helper",
"function",
"for",
"routes",
"and",
"gateways",
"to",
"create",
"qfilters",
"need",
"for",
"converted",
"subs",
"from",
"imports",
"etc",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L307-L315 |
164,211 | nats-io/gnatsd | server/route.go | processRouteInfo | func (c *client) processRouteInfo(info *Info) {
// We may need to update route permissions and will need the account
// sublist. Since getting the account requires server lock, do the
// lookup now.
// FIXME(dlc) - Add account scoping.
gacc := c.srv.globalAccount()
gacc.mu.RLock()
sl := gacc.sl
gacc.mu.RUnlock()
c.mu.Lock()
// Connection can be closed at any time (by auth timeout, etc).
// Does not make sense to continue here if connection is gone.
if c.route == nil || c.nc == nil {
c.mu.Unlock()
return
}
s := c.srv
remoteID := c.route.remoteID
// Check if this is an INFO for gateways...
if info.Gateway != "" {
c.mu.Unlock()
// If this server has no gateway configured, report error and return.
if !s.gateway.enabled {
// FIXME: Should this be a Fatalf()?
s.Errorf("Received information about gateway %q from %s, but gateway is not configured",
info.Gateway, remoteID)
return
}
s.processGatewayInfoFromRoute(info, remoteID, c)
return
}
// We receive an INFO from a server that informs us about another server,
// so the info.ID in the INFO protocol does not match the ID of this route.
if remoteID != "" && remoteID != info.ID {
c.mu.Unlock()
// Process this implicit route. We will check that it is not an explicit
// route and/or that it has not been connected already.
s.processImplicitRoute(info)
return
}
// Need to set this for the detection of the route to self to work
// in closeConnection().
c.route.remoteID = info.ID
// Get the route's proto version
c.opts.Protocol = info.Proto
// Detect route to self.
if c.route.remoteID == s.info.ID {
c.mu.Unlock()
c.closeConnection(DuplicateRoute)
return
}
// Copy over important information.
c.route.authRequired = info.AuthRequired
c.route.tlsRequired = info.TLSRequired
c.route.gatewayURL = info.GatewayURL
// When sent through route INFO, if the field is set, it should be of size 1.
if len(info.LeafNodeURLs) == 1 {
c.route.leafnodeURL = info.LeafNodeURLs[0]
}
// If this is an update due to config reload on the remote server,
// need to possibly send local subs to the remote server.
if c.flags.isSet(infoReceived) {
c.updateRemoteRoutePerms(sl, info)
c.mu.Unlock()
return
}
// Copy over permissions as well.
c.opts.Import = info.Import
c.opts.Export = info.Export
// If we do not know this route's URL, construct one on the fly
// from the information provided.
if c.route.url == nil {
// Add in the URL from host and port
hp := net.JoinHostPort(info.Host, strconv.Itoa(info.Port))
url, err := url.Parse(fmt.Sprintf("nats-route://%s/", hp))
if err != nil {
c.Errorf("Error parsing URL from INFO: %v\n", err)
c.mu.Unlock()
c.closeConnection(ParseError)
return
}
c.route.url = url
}
// Mark that the INFO protocol has been received. Will allow
// to detect INFO updates.
c.flags.set(infoReceived)
// Check to see if we have this remote already registered.
// This can happen when both servers have routes to each other.
c.mu.Unlock()
if added, sendInfo := s.addRoute(c, info); added {
c.Debugf("Registering remote route %q", info.ID)
// Send our subs to the other side.
s.sendSubsToRoute(c)
// Send info about the known gateways to this route.
s.sendGatewayConfigsToRoute(c)
// sendInfo will be false if the route that we just accepted
// is the only route there is.
if sendInfo {
// The incoming INFO from the route will have IP set
// if it has Cluster.Advertise. In that case, use that
// otherwise contruct it from the remote TCP address.
if info.IP == "" {
// Need to get the remote IP address.
c.mu.Lock()
switch conn := c.nc.(type) {
case *net.TCPConn, *tls.Conn:
addr := conn.RemoteAddr().(*net.TCPAddr)
info.IP = fmt.Sprintf("nats-route://%s/", net.JoinHostPort(addr.IP.String(),
strconv.Itoa(info.Port)))
default:
info.IP = c.route.url.String()
}
c.mu.Unlock()
}
// Now let the known servers know about this new route
s.forwardNewRouteInfoToKnownServers(info)
}
// Unless disabled, possibly update the server's INFO protocol
// and send to clients that know how to handle async INFOs.
if !s.getOpts().Cluster.NoAdvertise {
s.addClientConnectURLsAndSendINFOToClients(info.ClientConnectURLs)
}
} else {
c.Debugf("Detected duplicate remote route %q", info.ID)
c.closeConnection(DuplicateRoute)
}
} | go | func (c *client) processRouteInfo(info *Info) {
// We may need to update route permissions and will need the account
// sublist. Since getting the account requires server lock, do the
// lookup now.
// FIXME(dlc) - Add account scoping.
gacc := c.srv.globalAccount()
gacc.mu.RLock()
sl := gacc.sl
gacc.mu.RUnlock()
c.mu.Lock()
// Connection can be closed at any time (by auth timeout, etc).
// Does not make sense to continue here if connection is gone.
if c.route == nil || c.nc == nil {
c.mu.Unlock()
return
}
s := c.srv
remoteID := c.route.remoteID
// Check if this is an INFO for gateways...
if info.Gateway != "" {
c.mu.Unlock()
// If this server has no gateway configured, report error and return.
if !s.gateway.enabled {
// FIXME: Should this be a Fatalf()?
s.Errorf("Received information about gateway %q from %s, but gateway is not configured",
info.Gateway, remoteID)
return
}
s.processGatewayInfoFromRoute(info, remoteID, c)
return
}
// We receive an INFO from a server that informs us about another server,
// so the info.ID in the INFO protocol does not match the ID of this route.
if remoteID != "" && remoteID != info.ID {
c.mu.Unlock()
// Process this implicit route. We will check that it is not an explicit
// route and/or that it has not been connected already.
s.processImplicitRoute(info)
return
}
// Need to set this for the detection of the route to self to work
// in closeConnection().
c.route.remoteID = info.ID
// Get the route's proto version
c.opts.Protocol = info.Proto
// Detect route to self.
if c.route.remoteID == s.info.ID {
c.mu.Unlock()
c.closeConnection(DuplicateRoute)
return
}
// Copy over important information.
c.route.authRequired = info.AuthRequired
c.route.tlsRequired = info.TLSRequired
c.route.gatewayURL = info.GatewayURL
// When sent through route INFO, if the field is set, it should be of size 1.
if len(info.LeafNodeURLs) == 1 {
c.route.leafnodeURL = info.LeafNodeURLs[0]
}
// If this is an update due to config reload on the remote server,
// need to possibly send local subs to the remote server.
if c.flags.isSet(infoReceived) {
c.updateRemoteRoutePerms(sl, info)
c.mu.Unlock()
return
}
// Copy over permissions as well.
c.opts.Import = info.Import
c.opts.Export = info.Export
// If we do not know this route's URL, construct one on the fly
// from the information provided.
if c.route.url == nil {
// Add in the URL from host and port
hp := net.JoinHostPort(info.Host, strconv.Itoa(info.Port))
url, err := url.Parse(fmt.Sprintf("nats-route://%s/", hp))
if err != nil {
c.Errorf("Error parsing URL from INFO: %v\n", err)
c.mu.Unlock()
c.closeConnection(ParseError)
return
}
c.route.url = url
}
// Mark that the INFO protocol has been received. Will allow
// to detect INFO updates.
c.flags.set(infoReceived)
// Check to see if we have this remote already registered.
// This can happen when both servers have routes to each other.
c.mu.Unlock()
if added, sendInfo := s.addRoute(c, info); added {
c.Debugf("Registering remote route %q", info.ID)
// Send our subs to the other side.
s.sendSubsToRoute(c)
// Send info about the known gateways to this route.
s.sendGatewayConfigsToRoute(c)
// sendInfo will be false if the route that we just accepted
// is the only route there is.
if sendInfo {
// The incoming INFO from the route will have IP set
// if it has Cluster.Advertise. In that case, use that
// otherwise contruct it from the remote TCP address.
if info.IP == "" {
// Need to get the remote IP address.
c.mu.Lock()
switch conn := c.nc.(type) {
case *net.TCPConn, *tls.Conn:
addr := conn.RemoteAddr().(*net.TCPAddr)
info.IP = fmt.Sprintf("nats-route://%s/", net.JoinHostPort(addr.IP.String(),
strconv.Itoa(info.Port)))
default:
info.IP = c.route.url.String()
}
c.mu.Unlock()
}
// Now let the known servers know about this new route
s.forwardNewRouteInfoToKnownServers(info)
}
// Unless disabled, possibly update the server's INFO protocol
// and send to clients that know how to handle async INFOs.
if !s.getOpts().Cluster.NoAdvertise {
s.addClientConnectURLsAndSendINFOToClients(info.ClientConnectURLs)
}
} else {
c.Debugf("Detected duplicate remote route %q", info.ID)
c.closeConnection(DuplicateRoute)
}
} | [
"func",
"(",
"c",
"*",
"client",
")",
"processRouteInfo",
"(",
"info",
"*",
"Info",
")",
"{",
"// We may need to update route permissions and will need the account",
"// sublist. Since getting the account requires server lock, do the",
"// lookup now.",
"// FIXME(dlc) - Add account s... | // Process the info message if we are a route. | [
"Process",
"the",
"info",
"message",
"if",
"we",
"are",
"a",
"route",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L344-L489 |
164,212 | nats-io/gnatsd | server/route.go | updateRemoteRoutePerms | func (c *client) updateRemoteRoutePerms(sl *Sublist, info *Info) {
// Interested only on Export permissions for the remote server.
// Create "fake" clients that we will use to check permissions
// using the old permissions...
oldPerms := &RoutePermissions{Export: c.opts.Export}
oldPermsTester := &client{}
oldPermsTester.setRoutePermissions(oldPerms)
// and the new ones.
newPerms := &RoutePermissions{Export: info.Export}
newPermsTester := &client{}
newPermsTester.setRoutePermissions(newPerms)
c.opts.Import = info.Import
c.opts.Export = info.Export
var (
_localSubs [4096]*subscription
localSubs = _localSubs[:0]
)
sl.localSubs(&localSubs)
c.sendRouteSubProtos(localSubs, false, func(sub *subscription) bool {
subj := string(sub.subject)
// If the remote can now export but could not before, and this server can import this
// subject, then send SUB protocol.
if newPermsTester.canExport(subj) && !oldPermsTester.canExport(subj) && c.canImport(subj) {
return true
}
return false
})
} | go | func (c *client) updateRemoteRoutePerms(sl *Sublist, info *Info) {
// Interested only on Export permissions for the remote server.
// Create "fake" clients that we will use to check permissions
// using the old permissions...
oldPerms := &RoutePermissions{Export: c.opts.Export}
oldPermsTester := &client{}
oldPermsTester.setRoutePermissions(oldPerms)
// and the new ones.
newPerms := &RoutePermissions{Export: info.Export}
newPermsTester := &client{}
newPermsTester.setRoutePermissions(newPerms)
c.opts.Import = info.Import
c.opts.Export = info.Export
var (
_localSubs [4096]*subscription
localSubs = _localSubs[:0]
)
sl.localSubs(&localSubs)
c.sendRouteSubProtos(localSubs, false, func(sub *subscription) bool {
subj := string(sub.subject)
// If the remote can now export but could not before, and this server can import this
// subject, then send SUB protocol.
if newPermsTester.canExport(subj) && !oldPermsTester.canExport(subj) && c.canImport(subj) {
return true
}
return false
})
} | [
"func",
"(",
"c",
"*",
"client",
")",
"updateRemoteRoutePerms",
"(",
"sl",
"*",
"Sublist",
",",
"info",
"*",
"Info",
")",
"{",
"// Interested only on Export permissions for the remote server.",
"// Create \"fake\" clients that we will use to check permissions",
"// using the ol... | // Possibly sends local subscriptions interest to this route
// based on changes in the remote's Export permissions.
// Lock assumed held on entry | [
"Possibly",
"sends",
"local",
"subscriptions",
"interest",
"to",
"this",
"route",
"based",
"on",
"changes",
"in",
"the",
"remote",
"s",
"Export",
"permissions",
".",
"Lock",
"assumed",
"held",
"on",
"entry"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L494-L524 |
164,213 | nats-io/gnatsd | server/route.go | sendAsyncInfoToClients | func (s *Server) sendAsyncInfoToClients() {
// If there are no clients supporting async INFO protocols, we are done.
// Also don't send if we are shutting down...
if s.cproto == 0 || s.shutdown {
return
}
for _, c := range s.clients {
c.mu.Lock()
// Here, we are going to send only to the clients that are fully
// registered (server has received CONNECT and first PING). For
// clients that are not at this stage, this will happen in the
// processing of the first PING (see client.processPing)
if c.opts.Protocol >= ClientProtoInfo && c.flags.isSet(firstPongSent) {
// sendInfo takes care of checking if the connection is still
// valid or not, so don't duplicate tests here.
c.sendInfo(c.generateClientInfoJSON(s.copyInfo()))
}
c.mu.Unlock()
}
} | go | func (s *Server) sendAsyncInfoToClients() {
// If there are no clients supporting async INFO protocols, we are done.
// Also don't send if we are shutting down...
if s.cproto == 0 || s.shutdown {
return
}
for _, c := range s.clients {
c.mu.Lock()
// Here, we are going to send only to the clients that are fully
// registered (server has received CONNECT and first PING). For
// clients that are not at this stage, this will happen in the
// processing of the first PING (see client.processPing)
if c.opts.Protocol >= ClientProtoInfo && c.flags.isSet(firstPongSent) {
// sendInfo takes care of checking if the connection is still
// valid or not, so don't duplicate tests here.
c.sendInfo(c.generateClientInfoJSON(s.copyInfo()))
}
c.mu.Unlock()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendAsyncInfoToClients",
"(",
")",
"{",
"// If there are no clients supporting async INFO protocols, we are done.",
"// Also don't send if we are shutting down...",
"if",
"s",
".",
"cproto",
"==",
"0",
"||",
"s",
".",
"shutdown",
"{"... | // sendAsyncInfoToClients sends an INFO protocol to all
// connected clients that accept async INFO updates.
// The server lock is held on entry. | [
"sendAsyncInfoToClients",
"sends",
"an",
"INFO",
"protocol",
"to",
"all",
"connected",
"clients",
"that",
"accept",
"async",
"INFO",
"updates",
".",
"The",
"server",
"lock",
"is",
"held",
"on",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L529-L549 |
164,214 | nats-io/gnatsd | server/route.go | processImplicitRoute | func (s *Server) processImplicitRoute(info *Info) {
remoteID := info.ID
s.mu.Lock()
defer s.mu.Unlock()
// Don't connect to ourself
if remoteID == s.info.ID {
return
}
// Check if this route already exists
if _, exists := s.remotes[remoteID]; exists {
return
}
// Check if we have this route as a configured route
if s.hasThisRouteConfigured(info) {
return
}
// Initiate the connection, using info.IP instead of info.URL here...
r, err := url.Parse(info.IP)
if err != nil {
s.Errorf("Error parsing URL from INFO: %v\n", err)
return
}
// Snapshot server options.
opts := s.getOpts()
if info.AuthRequired {
r.User = url.UserPassword(opts.Cluster.Username, opts.Cluster.Password)
}
s.startGoRoutine(func() { s.connectToRoute(r, false) })
} | go | func (s *Server) processImplicitRoute(info *Info) {
remoteID := info.ID
s.mu.Lock()
defer s.mu.Unlock()
// Don't connect to ourself
if remoteID == s.info.ID {
return
}
// Check if this route already exists
if _, exists := s.remotes[remoteID]; exists {
return
}
// Check if we have this route as a configured route
if s.hasThisRouteConfigured(info) {
return
}
// Initiate the connection, using info.IP instead of info.URL here...
r, err := url.Parse(info.IP)
if err != nil {
s.Errorf("Error parsing URL from INFO: %v\n", err)
return
}
// Snapshot server options.
opts := s.getOpts()
if info.AuthRequired {
r.User = url.UserPassword(opts.Cluster.Username, opts.Cluster.Password)
}
s.startGoRoutine(func() { s.connectToRoute(r, false) })
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"processImplicitRoute",
"(",
"info",
"*",
"Info",
")",
"{",
"remoteID",
":=",
"info",
".",
"ID",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
... | // This will process implicit route information received from another server.
// We will check to see if we have configured or are already connected,
// and if so we will ignore. Otherwise we will attempt to connect. | [
"This",
"will",
"process",
"implicit",
"route",
"information",
"received",
"from",
"another",
"server",
".",
"We",
"will",
"check",
"to",
"see",
"if",
"we",
"have",
"configured",
"or",
"are",
"already",
"connected",
"and",
"if",
"so",
"we",
"will",
"ignore",... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L554-L587 |
164,215 | nats-io/gnatsd | server/route.go | forwardNewRouteInfoToKnownServers | func (s *Server) forwardNewRouteInfoToKnownServers(info *Info) {
s.mu.Lock()
defer s.mu.Unlock()
b, _ := json.Marshal(info)
infoJSON := []byte(fmt.Sprintf(InfoProto, b))
for _, r := range s.routes {
r.mu.Lock()
if r.route.remoteID != info.ID {
r.sendInfo(infoJSON)
}
r.mu.Unlock()
}
} | go | func (s *Server) forwardNewRouteInfoToKnownServers(info *Info) {
s.mu.Lock()
defer s.mu.Unlock()
b, _ := json.Marshal(info)
infoJSON := []byte(fmt.Sprintf(InfoProto, b))
for _, r := range s.routes {
r.mu.Lock()
if r.route.remoteID != info.ID {
r.sendInfo(infoJSON)
}
r.mu.Unlock()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"forwardNewRouteInfoToKnownServers",
"(",
"info",
"*",
"Info",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"b",
",",
"_",
":=",
"json",
"."... | // forwardNewRouteInfoToKnownServers sends the INFO protocol of the new route
// to all routes known by this server. In turn, each server will contact this
// new route. | [
"forwardNewRouteInfoToKnownServers",
"sends",
"the",
"INFO",
"protocol",
"of",
"the",
"new",
"route",
"to",
"all",
"routes",
"known",
"by",
"this",
"server",
".",
"In",
"turn",
"each",
"server",
"will",
"contact",
"this",
"new",
"route",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L605-L619 |
164,216 | nats-io/gnatsd | server/route.go | setRoutePermissions | func (c *client) setRoutePermissions(perms *RoutePermissions) {
// Reset if some were set
if perms == nil {
c.perms = nil
c.mperms = nil
return
}
// Convert route permissions to user permissions.
// The Import permission is mapped to Publish
// and Export permission is mapped to Subscribe.
// For meaning of Import/Export, see canImport and canExport.
p := &Permissions{
Publish: perms.Import,
Subscribe: perms.Export,
}
c.setPermissions(p)
} | go | func (c *client) setRoutePermissions(perms *RoutePermissions) {
// Reset if some were set
if perms == nil {
c.perms = nil
c.mperms = nil
return
}
// Convert route permissions to user permissions.
// The Import permission is mapped to Publish
// and Export permission is mapped to Subscribe.
// For meaning of Import/Export, see canImport and canExport.
p := &Permissions{
Publish: perms.Import,
Subscribe: perms.Export,
}
c.setPermissions(p)
} | [
"func",
"(",
"c",
"*",
"client",
")",
"setRoutePermissions",
"(",
"perms",
"*",
"RoutePermissions",
")",
"{",
"// Reset if some were set",
"if",
"perms",
"==",
"nil",
"{",
"c",
".",
"perms",
"=",
"nil",
"\n",
"c",
".",
"mperms",
"=",
"nil",
"\n",
"return... | // Initialize or reset cluster's permissions.
// This is for ROUTER connections only.
// Client lock is held on entry | [
"Initialize",
"or",
"reset",
"cluster",
"s",
"permissions",
".",
"This",
"is",
"for",
"ROUTER",
"connections",
"only",
".",
"Client",
"lock",
"is",
"held",
"on",
"entry"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L642-L658 |
164,217 | nats-io/gnatsd | server/route.go | removeRemoteSubs | func (c *client) removeRemoteSubs() {
// We need to gather these on a per account basis.
// FIXME(dlc) - We should be smarter about this..
as := map[string]*asubs{}
c.mu.Lock()
srv := c.srv
subs := c.subs
c.subs = make(map[string]*subscription)
c.mu.Unlock()
for key, sub := range subs {
c.mu.Lock()
sub.max = 0
c.mu.Unlock()
// Grab the account
accountName := strings.Fields(key)[0]
ase := as[accountName]
if ase == nil {
acc, _ := srv.LookupAccount(accountName)
if acc == nil {
continue
}
as[accountName] = &asubs{acc: acc, subs: []*subscription{sub}}
} else {
ase.subs = append(ase.subs, sub)
}
if srv.gateway.enabled {
srv.gatewayUpdateSubInterest(accountName, sub, -1)
}
}
// Now remove the subs by batch for each account sublist.
for _, ase := range as {
c.Debugf("Removing %d subscriptions for account %q", len(ase.subs), ase.acc.Name)
ase.acc.sl.RemoveBatch(ase.subs)
}
} | go | func (c *client) removeRemoteSubs() {
// We need to gather these on a per account basis.
// FIXME(dlc) - We should be smarter about this..
as := map[string]*asubs{}
c.mu.Lock()
srv := c.srv
subs := c.subs
c.subs = make(map[string]*subscription)
c.mu.Unlock()
for key, sub := range subs {
c.mu.Lock()
sub.max = 0
c.mu.Unlock()
// Grab the account
accountName := strings.Fields(key)[0]
ase := as[accountName]
if ase == nil {
acc, _ := srv.LookupAccount(accountName)
if acc == nil {
continue
}
as[accountName] = &asubs{acc: acc, subs: []*subscription{sub}}
} else {
ase.subs = append(ase.subs, sub)
}
if srv.gateway.enabled {
srv.gatewayUpdateSubInterest(accountName, sub, -1)
}
}
// Now remove the subs by batch for each account sublist.
for _, ase := range as {
c.Debugf("Removing %d subscriptions for account %q", len(ase.subs), ase.acc.Name)
ase.acc.sl.RemoveBatch(ase.subs)
}
} | [
"func",
"(",
"c",
"*",
"client",
")",
"removeRemoteSubs",
"(",
")",
"{",
"// We need to gather these on a per account basis.",
"// FIXME(dlc) - We should be smarter about this..",
"as",
":=",
"map",
"[",
"string",
"]",
"*",
"asubs",
"{",
"}",
"\n",
"c",
".",
"mu",
... | // removeRemoteSubs will walk the subs and remove them from the appropriate account. | [
"removeRemoteSubs",
"will",
"walk",
"the",
"subs",
"and",
"remove",
"them",
"from",
"the",
"appropriate",
"account",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L667-L703 |
164,218 | nats-io/gnatsd | server/route.go | sendSubsToRoute | func (s *Server) sendSubsToRoute(route *client) {
s.mu.Lock()
// Estimated size of all protocols. It does not have to be accurate at all.
eSize := 0
// Send over our account subscriptions.
// copy accounts into array first
accs := make([]*Account, 0, 32)
s.accounts.Range(func(k, v interface{}) bool {
a := v.(*Account)
accs = append(accs, a)
a.mu.RLock()
// Proto looks like: "RS+ <account name> <subject>[ <queue weight>]\r\n"
// If we wanted to have better estimates (or even accurate), we would
// collect the subs here instead of capturing the accounts and then
// later going over each account.
eSize += len(a.rm) * (4 + len(a.Name) + 256)
a.mu.RUnlock()
return true
})
s.mu.Unlock()
sendSubs := func(accs []*Account) {
var raw [32]*subscription
var closed bool
route.mu.Lock()
for _, a := range accs {
subs := raw[:0]
a.mu.RLock()
c := a.randomClient()
if c == nil {
a.mu.RUnlock()
continue
}
for key, n := range a.rm {
// FIXME(dlc) - Just pass rme around.
// Construct a sub on the fly. We need to place
// a client (or im) to properly set the account.
var subj, qn []byte
s := strings.Split(key, " ")
subj = []byte(s[0])
if len(s) > 1 {
qn = []byte(s[1])
}
// TODO(dlc) - This code needs to change, but even if left alone could be more
// efficient with these tmp subs.
sub := &subscription{client: c, subject: subj, queue: qn, qw: n}
subs = append(subs, sub)
}
a.mu.RUnlock()
closed = route.sendRouteSubProtos(subs, false, func(sub *subscription) bool {
return route.canImport(string(sub.subject))
})
if closed {
route.mu.Unlock()
return
}
}
route.mu.Unlock()
if !closed {
route.Debugf("Sent local subscriptions to route")
}
}
// Decide if we call above function in go routine or in place.
if eSize > sendRouteSubsInGoRoutineThreshold {
s.startGoRoutine(func() {
sendSubs(accs)
s.grWG.Done()
})
} else {
sendSubs(accs)
}
} | go | func (s *Server) sendSubsToRoute(route *client) {
s.mu.Lock()
// Estimated size of all protocols. It does not have to be accurate at all.
eSize := 0
// Send over our account subscriptions.
// copy accounts into array first
accs := make([]*Account, 0, 32)
s.accounts.Range(func(k, v interface{}) bool {
a := v.(*Account)
accs = append(accs, a)
a.mu.RLock()
// Proto looks like: "RS+ <account name> <subject>[ <queue weight>]\r\n"
// If we wanted to have better estimates (or even accurate), we would
// collect the subs here instead of capturing the accounts and then
// later going over each account.
eSize += len(a.rm) * (4 + len(a.Name) + 256)
a.mu.RUnlock()
return true
})
s.mu.Unlock()
sendSubs := func(accs []*Account) {
var raw [32]*subscription
var closed bool
route.mu.Lock()
for _, a := range accs {
subs := raw[:0]
a.mu.RLock()
c := a.randomClient()
if c == nil {
a.mu.RUnlock()
continue
}
for key, n := range a.rm {
// FIXME(dlc) - Just pass rme around.
// Construct a sub on the fly. We need to place
// a client (or im) to properly set the account.
var subj, qn []byte
s := strings.Split(key, " ")
subj = []byte(s[0])
if len(s) > 1 {
qn = []byte(s[1])
}
// TODO(dlc) - This code needs to change, but even if left alone could be more
// efficient with these tmp subs.
sub := &subscription{client: c, subject: subj, queue: qn, qw: n}
subs = append(subs, sub)
}
a.mu.RUnlock()
closed = route.sendRouteSubProtos(subs, false, func(sub *subscription) bool {
return route.canImport(string(sub.subject))
})
if closed {
route.mu.Unlock()
return
}
}
route.mu.Unlock()
if !closed {
route.Debugf("Sent local subscriptions to route")
}
}
// Decide if we call above function in go routine or in place.
if eSize > sendRouteSubsInGoRoutineThreshold {
s.startGoRoutine(func() {
sendSubs(accs)
s.grWG.Done()
})
} else {
sendSubs(accs)
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendSubsToRoute",
"(",
"route",
"*",
"client",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"// Estimated size of all protocols. It does not have to be accurate at all.",
"eSize",
":=",
"0",
"\n",
"// Send over our ... | // sendSubsToRoute will send over our subject interest to
// the remote side. For each account we will send the
// complete interest for all subjects, both normal as a binary
// and queue group weights. | [
"sendSubsToRoute",
"will",
"send",
"over",
"our",
"subject",
"interest",
"to",
"the",
"remote",
"side",
".",
"For",
"each",
"account",
"we",
"will",
"send",
"the",
"complete",
"interest",
"for",
"all",
"subjects",
"both",
"normal",
"as",
"a",
"binary",
"and"... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L887-L963 |
164,219 | nats-io/gnatsd | server/route.go | sendRouteSubProtos | func (c *client) sendRouteSubProtos(subs []*subscription, trace bool, filter func(sub *subscription) bool) bool {
return c.sendRouteSubOrUnSubProtos(subs, true, trace, filter)
} | go | func (c *client) sendRouteSubProtos(subs []*subscription, trace bool, filter func(sub *subscription) bool) bool {
return c.sendRouteSubOrUnSubProtos(subs, true, trace, filter)
} | [
"func",
"(",
"c",
"*",
"client",
")",
"sendRouteSubProtos",
"(",
"subs",
"[",
"]",
"*",
"subscription",
",",
"trace",
"bool",
",",
"filter",
"func",
"(",
"sub",
"*",
"subscription",
")",
"bool",
")",
"bool",
"{",
"return",
"c",
".",
"sendRouteSubOrUnSubP... | // Sends SUBs protocols for the given subscriptions. If a filter is specified, it is
// invoked for each subscription. If the filter returns false, the subscription is skipped.
// This function may release the route's lock due to flushing of outbound data. A boolean
// is returned to indicate if the connection has been closed during this call.
// Lock is held on entry. | [
"Sends",
"SUBs",
"protocols",
"for",
"the",
"given",
"subscriptions",
".",
"If",
"a",
"filter",
"is",
"specified",
"it",
"is",
"invoked",
"for",
"each",
"subscription",
".",
"If",
"the",
"filter",
"returns",
"false",
"the",
"subscription",
"is",
"skipped",
"... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L970-L972 |
164,220 | nats-io/gnatsd | server/route.go | sendRouteUnSubProtos | func (c *client) sendRouteUnSubProtos(subs []*subscription, trace bool, filter func(sub *subscription) bool) bool {
return c.sendRouteSubOrUnSubProtos(subs, false, trace, filter)
} | go | func (c *client) sendRouteUnSubProtos(subs []*subscription, trace bool, filter func(sub *subscription) bool) bool {
return c.sendRouteSubOrUnSubProtos(subs, false, trace, filter)
} | [
"func",
"(",
"c",
"*",
"client",
")",
"sendRouteUnSubProtos",
"(",
"subs",
"[",
"]",
"*",
"subscription",
",",
"trace",
"bool",
",",
"filter",
"func",
"(",
"sub",
"*",
"subscription",
")",
"bool",
")",
"bool",
"{",
"return",
"c",
".",
"sendRouteSubOrUnSu... | // Sends UNSUBs protocols for the given subscriptions. If a filter is specified, it is
// invoked for each subscription. If the filter returns false, the subscription is skipped.
// This function may release the route's lock due to flushing of outbound data. A boolean
// is returned to indicate if the connection has been closed during this call.
// Lock is held on entry. | [
"Sends",
"UNSUBs",
"protocols",
"for",
"the",
"given",
"subscriptions",
".",
"If",
"a",
"filter",
"is",
"specified",
"it",
"is",
"invoked",
"for",
"each",
"subscription",
".",
"If",
"the",
"filter",
"returns",
"false",
"the",
"subscription",
"is",
"skipped",
... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L979-L981 |
164,221 | nats-io/gnatsd | server/route.go | updateRouteSubscriptionMap | func (s *Server) updateRouteSubscriptionMap(acc *Account, sub *subscription, delta int32) {
if acc == nil || sub == nil {
return
}
acc.mu.RLock()
rm := acc.rm
acc.mu.RUnlock()
// This is non-nil when we know we are in cluster mode.
if rm == nil {
return
}
// We only store state on local subs for transmission across all other routes.
if sub.client == nil || (sub.client.kind != CLIENT && sub.client.kind != SYSTEM && sub.client.kind != LEAF) {
return
}
// Create the fast key which will use the subject or 'subject<spc>queue' for queue subscribers.
var (
_rkey [1024]byte
key []byte
update bool
)
if sub.queue != nil {
// Just make the key subject spc group, e.g. 'foo bar'
key = _rkey[:0]
key = append(key, sub.subject...)
key = append(key, byte(' '))
key = append(key, sub.queue...)
// We always update for a queue subscriber since we need to send our relative weight.
update = true
} else {
key = sub.subject
}
// Copy to hold outside acc lock.
var n int32
var ok bool
acc.mu.Lock()
if n, ok = rm[string(key)]; ok {
n += delta
if n <= 0 {
delete(rm, string(key))
update = true // Update for deleting (N->0)
} else {
rm[string(key)] = n
}
} else if delta > 0 {
n = delta
rm[string(key)] = delta
update = true // Adding a new entry for normal sub means update (0->1)
}
acc.mu.Unlock()
if !update {
return
}
// We need to send out this update.
// If we are sending a queue sub, copy and place in the queue weight.
if sub.queue != nil {
sub.client.mu.Lock()
nsub := *sub
sub.client.mu.Unlock()
nsub.qw = n
sub = &nsub
}
// Note that queue unsubs where entry.n > 0 are still
// subscribes with a smaller weight.
if n > 0 {
s.broadcastSubscribe(sub)
} else {
s.broadcastUnSubscribe(sub)
}
} | go | func (s *Server) updateRouteSubscriptionMap(acc *Account, sub *subscription, delta int32) {
if acc == nil || sub == nil {
return
}
acc.mu.RLock()
rm := acc.rm
acc.mu.RUnlock()
// This is non-nil when we know we are in cluster mode.
if rm == nil {
return
}
// We only store state on local subs for transmission across all other routes.
if sub.client == nil || (sub.client.kind != CLIENT && sub.client.kind != SYSTEM && sub.client.kind != LEAF) {
return
}
// Create the fast key which will use the subject or 'subject<spc>queue' for queue subscribers.
var (
_rkey [1024]byte
key []byte
update bool
)
if sub.queue != nil {
// Just make the key subject spc group, e.g. 'foo bar'
key = _rkey[:0]
key = append(key, sub.subject...)
key = append(key, byte(' '))
key = append(key, sub.queue...)
// We always update for a queue subscriber since we need to send our relative weight.
update = true
} else {
key = sub.subject
}
// Copy to hold outside acc lock.
var n int32
var ok bool
acc.mu.Lock()
if n, ok = rm[string(key)]; ok {
n += delta
if n <= 0 {
delete(rm, string(key))
update = true // Update for deleting (N->0)
} else {
rm[string(key)] = n
}
} else if delta > 0 {
n = delta
rm[string(key)] = delta
update = true // Adding a new entry for normal sub means update (0->1)
}
acc.mu.Unlock()
if !update {
return
}
// We need to send out this update.
// If we are sending a queue sub, copy and place in the queue weight.
if sub.queue != nil {
sub.client.mu.Lock()
nsub := *sub
sub.client.mu.Unlock()
nsub.qw = n
sub = &nsub
}
// Note that queue unsubs where entry.n > 0 are still
// subscribes with a smaller weight.
if n > 0 {
s.broadcastSubscribe(sub)
} else {
s.broadcastUnSubscribe(sub)
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"updateRouteSubscriptionMap",
"(",
"acc",
"*",
"Account",
",",
"sub",
"*",
"subscription",
",",
"delta",
"int32",
")",
"{",
"if",
"acc",
"==",
"nil",
"||",
"sub",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"acc... | // updateRouteSubscriptionMap will make sure to update the route map for the subscription. Will
// also forward to all routes if needed. | [
"updateRouteSubscriptionMap",
"will",
"make",
"sure",
"to",
"update",
"the",
"route",
"map",
"for",
"the",
"subscription",
".",
"Will",
"also",
"forward",
"to",
"all",
"routes",
"if",
"needed",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L1298-L1375 |
164,222 | nats-io/gnatsd | server/route.go | broadcastUnSubscribe | func (s *Server) broadcastUnSubscribe(sub *subscription) {
trace := atomic.LoadInt32(&s.logging.trace) == 1
s.mu.Lock()
subs := []*subscription{sub}
for _, route := range s.routes {
route.mu.Lock()
route.sendRouteUnSubProtos(subs, trace, func(sub *subscription) bool {
return route.canImport(string(sub.subject))
})
route.mu.Unlock()
}
s.mu.Unlock()
} | go | func (s *Server) broadcastUnSubscribe(sub *subscription) {
trace := atomic.LoadInt32(&s.logging.trace) == 1
s.mu.Lock()
subs := []*subscription{sub}
for _, route := range s.routes {
route.mu.Lock()
route.sendRouteUnSubProtos(subs, trace, func(sub *subscription) bool {
return route.canImport(string(sub.subject))
})
route.mu.Unlock()
}
s.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"broadcastUnSubscribe",
"(",
"sub",
"*",
"subscription",
")",
"{",
"trace",
":=",
"atomic",
".",
"LoadInt32",
"(",
"&",
"s",
".",
"logging",
".",
"trace",
")",
"==",
"1",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",... | // broadcastUnSubscribe will forward a client unsubscribe
// action to all active routes. | [
"broadcastUnSubscribe",
"will",
"forward",
"a",
"client",
"unsubscribe",
"action",
"to",
"all",
"active",
"routes",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L1395-L1407 |
164,223 | nats-io/gnatsd | server/route.go | setRouteInfoHostPortAndIP | func (s *Server) setRouteInfoHostPortAndIP() error {
if s.opts.Cluster.Advertise != "" {
advHost, advPort, err := parseHostPort(s.opts.Cluster.Advertise, s.opts.Cluster.Port)
if err != nil {
return err
}
s.routeInfo.Host = advHost
s.routeInfo.Port = advPort
s.routeInfo.IP = fmt.Sprintf("nats-route://%s/", net.JoinHostPort(advHost, strconv.Itoa(advPort)))
} else {
s.routeInfo.Host = s.opts.Cluster.Host
s.routeInfo.Port = s.opts.Cluster.Port
s.routeInfo.IP = ""
}
// (re)generate the routeInfoJSON byte array
s.generateRouteInfoJSON()
return nil
} | go | func (s *Server) setRouteInfoHostPortAndIP() error {
if s.opts.Cluster.Advertise != "" {
advHost, advPort, err := parseHostPort(s.opts.Cluster.Advertise, s.opts.Cluster.Port)
if err != nil {
return err
}
s.routeInfo.Host = advHost
s.routeInfo.Port = advPort
s.routeInfo.IP = fmt.Sprintf("nats-route://%s/", net.JoinHostPort(advHost, strconv.Itoa(advPort)))
} else {
s.routeInfo.Host = s.opts.Cluster.Host
s.routeInfo.Port = s.opts.Cluster.Port
s.routeInfo.IP = ""
}
// (re)generate the routeInfoJSON byte array
s.generateRouteInfoJSON()
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"setRouteInfoHostPortAndIP",
"(",
")",
"error",
"{",
"if",
"s",
".",
"opts",
".",
"Cluster",
".",
"Advertise",
"!=",
"\"",
"\"",
"{",
"advHost",
",",
"advPort",
",",
"err",
":=",
"parseHostPort",
"(",
"s",
".",
"... | // Similar to setInfoHostPortAndGenerateJSON, but for routeInfo. | [
"Similar",
"to",
"setInfoHostPortAndGenerateJSON",
"but",
"for",
"routeInfo",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L1517-L1534 |
164,224 | nats-io/gnatsd | server/route.go | routeStillValid | func (s *Server) routeStillValid(rURL *url.URL) bool {
for _, ri := range s.getOpts().Routes {
if urlsAreEqual(ri, rURL) {
return true
}
}
return false
} | go | func (s *Server) routeStillValid(rURL *url.URL) bool {
for _, ri := range s.getOpts().Routes {
if urlsAreEqual(ri, rURL) {
return true
}
}
return false
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"routeStillValid",
"(",
"rURL",
"*",
"url",
".",
"URL",
")",
"bool",
"{",
"for",
"_",
",",
"ri",
":=",
"range",
"s",
".",
"getOpts",
"(",
")",
".",
"Routes",
"{",
"if",
"urlsAreEqual",
"(",
"ri",
",",
"rURL",... | // Checks to make sure the route is still valid. | [
"Checks",
"to",
"make",
"sure",
"the",
"route",
"is",
"still",
"valid",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/route.go#L1575-L1582 |
164,225 | nats-io/gnatsd | logger/syslog_windows.go | NewSysLogger | func NewSysLogger(debug, trace bool) *SysLogger {
if err := eventlog.InstallAsEventCreate(natsEventSource, eventlog.Info|eventlog.Error|eventlog.Warning); err != nil {
if !strings.Contains(err.Error(), "registry key already exists") {
panic(fmt.Sprintf("could not access event log: %v", err))
}
}
w, err := eventlog.Open(natsEventSource)
if err != nil {
panic(fmt.Sprintf("could not open event log: %v", err))
}
return &SysLogger{
writer: w,
debug: debug,
trace: trace,
}
} | go | func NewSysLogger(debug, trace bool) *SysLogger {
if err := eventlog.InstallAsEventCreate(natsEventSource, eventlog.Info|eventlog.Error|eventlog.Warning); err != nil {
if !strings.Contains(err.Error(), "registry key already exists") {
panic(fmt.Sprintf("could not access event log: %v", err))
}
}
w, err := eventlog.Open(natsEventSource)
if err != nil {
panic(fmt.Sprintf("could not open event log: %v", err))
}
return &SysLogger{
writer: w,
debug: debug,
trace: trace,
}
} | [
"func",
"NewSysLogger",
"(",
"debug",
",",
"trace",
"bool",
")",
"*",
"SysLogger",
"{",
"if",
"err",
":=",
"eventlog",
".",
"InstallAsEventCreate",
"(",
"natsEventSource",
",",
"eventlog",
".",
"Info",
"|",
"eventlog",
".",
"Error",
"|",
"eventlog",
".",
"... | // NewSysLogger creates a log using the windows event logger | [
"NewSysLogger",
"creates",
"a",
"log",
"using",
"the",
"windows",
"event",
"logger"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/logger/syslog_windows.go#L40-L57 |
164,226 | nats-io/gnatsd | logger/syslog_windows.go | NewRemoteSysLogger | func NewRemoteSysLogger(fqn string, debug, trace bool) *SysLogger {
w, err := eventlog.OpenRemote(fqn, natsEventSource)
if err != nil {
panic(fmt.Sprintf("could not open event log: %v", err))
}
return &SysLogger{
writer: w,
debug: debug,
trace: trace,
}
} | go | func NewRemoteSysLogger(fqn string, debug, trace bool) *SysLogger {
w, err := eventlog.OpenRemote(fqn, natsEventSource)
if err != nil {
panic(fmt.Sprintf("could not open event log: %v", err))
}
return &SysLogger{
writer: w,
debug: debug,
trace: trace,
}
} | [
"func",
"NewRemoteSysLogger",
"(",
"fqn",
"string",
",",
"debug",
",",
"trace",
"bool",
")",
"*",
"SysLogger",
"{",
"w",
",",
"err",
":=",
"eventlog",
".",
"OpenRemote",
"(",
"fqn",
",",
"natsEventSource",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"pan... | // NewRemoteSysLogger creates a remote event logger | [
"NewRemoteSysLogger",
"creates",
"a",
"remote",
"event",
"logger"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/logger/syslog_windows.go#L60-L71 |
164,227 | nats-io/gnatsd | server/ring.go | newClosedRingBuffer | func newClosedRingBuffer(max int) *closedRingBuffer {
rb := &closedRingBuffer{}
rb.conns = make([]*closedClient, max)
return rb
} | go | func newClosedRingBuffer(max int) *closedRingBuffer {
rb := &closedRingBuffer{}
rb.conns = make([]*closedClient, max)
return rb
} | [
"func",
"newClosedRingBuffer",
"(",
"max",
"int",
")",
"*",
"closedRingBuffer",
"{",
"rb",
":=",
"&",
"closedRingBuffer",
"{",
"}",
"\n",
"rb",
".",
"conns",
"=",
"make",
"(",
"[",
"]",
"*",
"closedClient",
",",
"max",
")",
"\n",
"return",
"rb",
"\n",
... | // Create a new ring buffer with at most max items. | [
"Create",
"a",
"new",
"ring",
"buffer",
"with",
"at",
"most",
"max",
"items",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/ring.go#L30-L34 |
164,228 | nats-io/gnatsd | server/ring.go | append | func (rb *closedRingBuffer) append(cc *closedClient) {
rb.conns[rb.next()] = cc
rb.total++
} | go | func (rb *closedRingBuffer) append(cc *closedClient) {
rb.conns[rb.next()] = cc
rb.total++
} | [
"func",
"(",
"rb",
"*",
"closedRingBuffer",
")",
"append",
"(",
"cc",
"*",
"closedClient",
")",
"{",
"rb",
".",
"conns",
"[",
"rb",
".",
"next",
"(",
")",
"]",
"=",
"cc",
"\n",
"rb",
".",
"total",
"++",
"\n",
"}"
] | // Adds in a new closed connection. If there is no more room,
// remove the oldest. | [
"Adds",
"in",
"a",
"new",
"closed",
"connection",
".",
"If",
"there",
"is",
"no",
"more",
"room",
"remove",
"the",
"oldest",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/ring.go#L38-L41 |
164,229 | nats-io/gnatsd | server/ring.go | closedClients | func (rb *closedRingBuffer) closedClients() []*closedClient {
dup := make([]*closedClient, rb.len())
head := rb.next()
if rb.total <= uint64(cap(rb.conns)) || head == 0 {
copy(dup, rb.conns[:rb.len()])
} else {
fp := rb.conns[head:]
sp := rb.conns[:head]
copy(dup, fp)
copy(dup[len(fp):], sp)
}
return dup
} | go | func (rb *closedRingBuffer) closedClients() []*closedClient {
dup := make([]*closedClient, rb.len())
head := rb.next()
if rb.total <= uint64(cap(rb.conns)) || head == 0 {
copy(dup, rb.conns[:rb.len()])
} else {
fp := rb.conns[head:]
sp := rb.conns[:head]
copy(dup, fp)
copy(dup[len(fp):], sp)
}
return dup
} | [
"func",
"(",
"rb",
"*",
"closedRingBuffer",
")",
"closedClients",
"(",
")",
"[",
"]",
"*",
"closedClient",
"{",
"dup",
":=",
"make",
"(",
"[",
"]",
"*",
"closedClient",
",",
"rb",
".",
"len",
"(",
")",
")",
"\n",
"head",
":=",
"rb",
".",
"next",
... | // This will return a sorted copy of the list which recipient can
// modify. If the contents of the client itself need to be modified,
// meaning swapping in any optional items, a copy should be made. We
// could introduce a new lock and hold that but since we return this
// list inside monitor which allows programatic access, we do not
// know when it would be done. | [
"This",
"will",
"return",
"a",
"sorted",
"copy",
"of",
"the",
"list",
"which",
"recipient",
"can",
"modify",
".",
"If",
"the",
"contents",
"of",
"the",
"client",
"itself",
"need",
"to",
"be",
"modified",
"meaning",
"swapping",
"in",
"any",
"optional",
"ite... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/ring.go#L64-L76 |
164,230 | nats-io/gnatsd | server/service_windows.go | Run | func Run(server *Server) error {
if dockerized {
server.Start()
return nil
}
run := svc.Run
isInteractive, err := svc.IsAnInteractiveSession()
if err != nil {
return err
}
if isInteractive {
run = debug.Run
}
return run(serviceName, &winServiceWrapper{server})
} | go | func Run(server *Server) error {
if dockerized {
server.Start()
return nil
}
run := svc.Run
isInteractive, err := svc.IsAnInteractiveSession()
if err != nil {
return err
}
if isInteractive {
run = debug.Run
}
return run(serviceName, &winServiceWrapper{server})
} | [
"func",
"Run",
"(",
"server",
"*",
"Server",
")",
"error",
"{",
"if",
"dockerized",
"{",
"server",
".",
"Start",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"run",
":=",
"svc",
".",
"Run",
"\n",
"isInteractive",
",",
"err",
":=",
"svc",
".",
... | // Run starts the NATS server as a Windows service. | [
"Run",
"starts",
"the",
"NATS",
"server",
"as",
"a",
"Windows",
"service",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/service_windows.go#L108-L122 |
164,231 | nats-io/gnatsd | server/accounts.go | shallowCopy | func (a *Account) shallowCopy() *Account {
na := NewAccount(a.Name)
na.Nkey = a.Nkey
na.Issuer = a.Issuer
na.imports = a.imports
na.exports = a.exports
return na
} | go | func (a *Account) shallowCopy() *Account {
na := NewAccount(a.Name)
na.Nkey = a.Nkey
na.Issuer = a.Issuer
na.imports = a.imports
na.exports = a.exports
return na
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"shallowCopy",
"(",
")",
"*",
"Account",
"{",
"na",
":=",
"NewAccount",
"(",
"a",
".",
"Name",
")",
"\n",
"na",
".",
"Nkey",
"=",
"a",
".",
"Nkey",
"\n",
"na",
".",
"Issuer",
"=",
"a",
".",
"Issuer",
"\n",... | // Used to create shallow copies of accounts for transfer
// from opts to real accounts in server struct. | [
"Used",
"to",
"create",
"shallow",
"copies",
"of",
"accounts",
"for",
"transfer",
"from",
"opts",
"to",
"real",
"accounts",
"in",
"server",
"struct",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L129-L136 |
164,232 | nats-io/gnatsd | server/accounts.go | NumConnections | func (a *Account) NumConnections() int {
a.mu.RLock()
nc := len(a.clients) + int(a.nrclients)
a.mu.RUnlock()
return nc
} | go | func (a *Account) NumConnections() int {
a.mu.RLock()
nc := len(a.clients) + int(a.nrclients)
a.mu.RUnlock()
return nc
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"NumConnections",
"(",
")",
"int",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"nc",
":=",
"len",
"(",
"a",
".",
"clients",
")",
"+",
"int",
"(",
"a",
".",
"nrclients",
")",
"\n",
"a",
".",
"mu",
... | // NumClients returns active number of clients for this account for
// all known servers. | [
"NumClients",
"returns",
"active",
"number",
"of",
"clients",
"for",
"this",
"account",
"for",
"all",
"known",
"servers",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L140-L145 |
164,233 | nats-io/gnatsd | server/accounts.go | NumLocalConnections | func (a *Account) NumLocalConnections() int {
a.mu.RLock()
nlc := a.numLocalConnections()
a.mu.RUnlock()
return nlc
} | go | func (a *Account) NumLocalConnections() int {
a.mu.RLock()
nlc := a.numLocalConnections()
a.mu.RUnlock()
return nlc
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"NumLocalConnections",
"(",
")",
"int",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"nlc",
":=",
"a",
".",
"numLocalConnections",
"(",
")",
"\n",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"retur... | // NumLocalClients returns active number of clients for this account
// on this server. | [
"NumLocalClients",
"returns",
"active",
"number",
"of",
"clients",
"for",
"this",
"account",
"on",
"this",
"server",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L149-L154 |
164,234 | nats-io/gnatsd | server/accounts.go | numLocalConnections | func (a *Account) numLocalConnections() int {
return len(a.clients) - int(a.sysclients) - int(a.nleafs)
} | go | func (a *Account) numLocalConnections() int {
return len(a.clients) - int(a.sysclients) - int(a.nleafs)
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"numLocalConnections",
"(",
")",
"int",
"{",
"return",
"len",
"(",
"a",
".",
"clients",
")",
"-",
"int",
"(",
"a",
".",
"sysclients",
")",
"-",
"int",
"(",
"a",
".",
"nleafs",
")",
"\n",
"}"
] | // Do not account for the system accounts. | [
"Do",
"not",
"account",
"for",
"the",
"system",
"accounts",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L157-L159 |
164,235 | nats-io/gnatsd | server/accounts.go | MaxTotalConnectionsReached | func (a *Account) MaxTotalConnectionsReached() bool {
a.mu.RLock()
mtc := a.maxTotalConnectionsReached()
a.mu.RUnlock()
return mtc
} | go | func (a *Account) MaxTotalConnectionsReached() bool {
a.mu.RLock()
mtc := a.maxTotalConnectionsReached()
a.mu.RUnlock()
return mtc
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"MaxTotalConnectionsReached",
"(",
")",
"bool",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"mtc",
":=",
"a",
".",
"maxTotalConnectionsReached",
"(",
")",
"\n",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
... | // MaxTotalConnectionsReached returns if we have reached our limit for number of connections. | [
"MaxTotalConnectionsReached",
"returns",
"if",
"we",
"have",
"reached",
"our",
"limit",
"for",
"number",
"of",
"connections",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L166-L171 |
164,236 | nats-io/gnatsd | server/accounts.go | MaxActiveConnections | func (a *Account) MaxActiveConnections() int {
a.mu.RLock()
mconns := int(a.mconns)
a.mu.RUnlock()
return mconns
} | go | func (a *Account) MaxActiveConnections() int {
a.mu.RLock()
mconns := int(a.mconns)
a.mu.RUnlock()
return mconns
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"MaxActiveConnections",
"(",
")",
"int",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"mconns",
":=",
"int",
"(",
"a",
".",
"mconns",
")",
"\n",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"retur... | // MaxActiveConnections return the set limit for the account system
// wide for total number of active connections. | [
"MaxActiveConnections",
"return",
"the",
"set",
"limit",
"for",
"the",
"account",
"system",
"wide",
"for",
"total",
"number",
"of",
"active",
"connections",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L182-L187 |
164,237 | nats-io/gnatsd | server/accounts.go | NumLeafNodes | func (a *Account) NumLeafNodes() int {
a.mu.RLock()
nln := int(a.nleafs + a.nrleafs)
a.mu.RUnlock()
return nln
} | go | func (a *Account) NumLeafNodes() int {
a.mu.RLock()
nln := int(a.nleafs + a.nrleafs)
a.mu.RUnlock()
return nln
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"NumLeafNodes",
"(",
")",
"int",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"nln",
":=",
"int",
"(",
"a",
".",
"nleafs",
"+",
"a",
".",
"nrleafs",
")",
"\n",
"a",
".",
"mu",
".",
"RUnlock",
"(",
... | // NumLeafNodes returns the active number of local and remote
// leaf node connections. | [
"NumLeafNodes",
"returns",
"the",
"active",
"number",
"of",
"local",
"and",
"remote",
"leaf",
"node",
"connections",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L206-L211 |
164,238 | nats-io/gnatsd | server/accounts.go | NumRemoteLeafNodes | func (a *Account) NumRemoteLeafNodes() int {
a.mu.RLock()
nrn := int(a.nrleafs)
a.mu.RUnlock()
return nrn
} | go | func (a *Account) NumRemoteLeafNodes() int {
a.mu.RLock()
nrn := int(a.nrleafs)
a.mu.RUnlock()
return nrn
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"NumRemoteLeafNodes",
"(",
")",
"int",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"nrn",
":=",
"int",
"(",
"a",
".",
"nrleafs",
")",
"\n",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
... | // NumRemoteLeafNodes returns the active number of remote
// leaf node connections. | [
"NumRemoteLeafNodes",
"returns",
"the",
"active",
"number",
"of",
"remote",
"leaf",
"node",
"connections",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L215-L220 |
164,239 | nats-io/gnatsd | server/accounts.go | RoutedSubs | func (a *Account) RoutedSubs() int {
a.mu.RLock()
defer a.mu.RUnlock()
return len(a.rm)
} | go | func (a *Account) RoutedSubs() int {
a.mu.RLock()
defer a.mu.RUnlock()
return len(a.rm)
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"RoutedSubs",
"(",
")",
"int",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"len",
"(",
"a",
".",
"rm",
")",
"\n",
"}"
] | // RoutedSubs returns how many subjects we would send across a route when first
// connected or expressing interest. Local client subs. | [
"RoutedSubs",
"returns",
"how",
"many",
"subjects",
"we",
"would",
"send",
"across",
"a",
"route",
"when",
"first",
"connected",
"or",
"expressing",
"interest",
".",
"Local",
"client",
"subs",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L234-L238 |
164,240 | nats-io/gnatsd | server/accounts.go | TotalSubs | func (a *Account) TotalSubs() int {
a.mu.RLock()
defer a.mu.RUnlock()
return int(a.sl.Count())
} | go | func (a *Account) TotalSubs() int {
a.mu.RLock()
defer a.mu.RUnlock()
return int(a.sl.Count())
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"TotalSubs",
"(",
")",
"int",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"int",
"(",
"a",
".",
"sl",
".",
"Count",
"(",
")",
"... | // TotalSubs returns total number of Subscriptions for this account. | [
"TotalSubs",
"returns",
"total",
"number",
"of",
"Subscriptions",
"for",
"this",
"account",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L241-L245 |
164,241 | nats-io/gnatsd | server/accounts.go | addClient | func (a *Account) addClient(c *client) int {
a.mu.Lock()
n := len(a.clients)
if a.clients != nil {
a.clients[c] = c
}
added := n != len(a.clients)
if added {
if c.kind == SYSTEM {
a.sysclients++
} else if c.kind == LEAF {
a.nleafs++
}
}
a.mu.Unlock()
if c != nil && c.srv != nil && a != c.srv.gacc && added {
c.srv.accConnsUpdate(a)
}
return n
} | go | func (a *Account) addClient(c *client) int {
a.mu.Lock()
n := len(a.clients)
if a.clients != nil {
a.clients[c] = c
}
added := n != len(a.clients)
if added {
if c.kind == SYSTEM {
a.sysclients++
} else if c.kind == LEAF {
a.nleafs++
}
}
a.mu.Unlock()
if c != nil && c.srv != nil && a != c.srv.gacc && added {
c.srv.accConnsUpdate(a)
}
return n
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"addClient",
"(",
"c",
"*",
"client",
")",
"int",
"{",
"a",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"n",
":=",
"len",
"(",
"a",
".",
"clients",
")",
"\n",
"if",
"a",
".",
"clients",
"!=",
"nil",
"{",
"... | // addClient keeps our accounting of local active clients or leafnodes updated.
// Returns previous total. | [
"addClient",
"keeps",
"our",
"accounting",
"of",
"local",
"active",
"clients",
"or",
"leafnodes",
"updated",
".",
"Returns",
"previous",
"total",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L249-L268 |
164,242 | nats-io/gnatsd | server/accounts.go | numServiceRoutes | func (a *Account) numServiceRoutes() int {
a.mu.RLock()
defer a.mu.RUnlock()
return len(a.imports.services)
} | go | func (a *Account) numServiceRoutes() int {
a.mu.RLock()
defer a.mu.RUnlock()
return len(a.imports.services)
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"numServiceRoutes",
"(",
")",
"int",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"len",
"(",
"a",
".",
"imports",
".",
"services",
... | // numServiceRoutes returns the number of service routes on this account. | [
"numServiceRoutes",
"returns",
"the",
"number",
"of",
"service",
"routes",
"on",
"this",
"account",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L330-L334 |
164,243 | nats-io/gnatsd | server/accounts.go | removeServiceImport | func (a *Account) removeServiceImport(subject string) {
a.mu.Lock()
si, ok := a.imports.services[subject]
if ok && si != nil && si.ae {
a.nae--
}
delete(a.imports.services, subject)
a.mu.Unlock()
if a.srv != nil && a.srv.gateway.enabled {
a.srv.gatewayHandleServiceImport(a, []byte(subject), nil, -1)
}
} | go | func (a *Account) removeServiceImport(subject string) {
a.mu.Lock()
si, ok := a.imports.services[subject]
if ok && si != nil && si.ae {
a.nae--
}
delete(a.imports.services, subject)
a.mu.Unlock()
if a.srv != nil && a.srv.gateway.enabled {
a.srv.gatewayHandleServiceImport(a, []byte(subject), nil, -1)
}
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"removeServiceImport",
"(",
"subject",
"string",
")",
"{",
"a",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"si",
",",
"ok",
":=",
"a",
".",
"imports",
".",
"services",
"[",
"subject",
"]",
"\n",
"if",
"ok",
"&&... | // removeServiceImport will remove the route by subject. | [
"removeServiceImport",
"will",
"remove",
"the",
"route",
"by",
"subject",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L364-L375 |
164,244 | nats-io/gnatsd | server/accounts.go | MaxAutoExpireResponseMaps | func (a *Account) MaxAutoExpireResponseMaps() int {
a.mu.RLock()
defer a.mu.RUnlock()
return int(a.maxnae)
} | go | func (a *Account) MaxAutoExpireResponseMaps() int {
a.mu.RLock()
defer a.mu.RUnlock()
return int(a.maxnae)
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"MaxAutoExpireResponseMaps",
"(",
")",
"int",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"int",
"(",
"a",
".",
"maxnae",
")",
"\n",
... | // MaxAutoExpireResponseMaps return the maximum number of
// auto expire response maps we will allow. | [
"MaxAutoExpireResponseMaps",
"return",
"the",
"maximum",
"number",
"of",
"auto",
"expire",
"response",
"maps",
"we",
"will",
"allow",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L387-L391 |
164,245 | nats-io/gnatsd | server/accounts.go | SetMaxAutoExpireResponseMaps | func (a *Account) SetMaxAutoExpireResponseMaps(max int) {
a.mu.Lock()
defer a.mu.Unlock()
a.maxnae = int32(max)
} | go | func (a *Account) SetMaxAutoExpireResponseMaps(max int) {
a.mu.Lock()
defer a.mu.Unlock()
a.maxnae = int32(max)
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"SetMaxAutoExpireResponseMaps",
"(",
"max",
"int",
")",
"{",
"a",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"a",
".",
"maxnae",
"=",
"int32",
"(",
"max",... | // SetMaxAutoExpireResponseMaps sets the max outstanding auto expire response maps. | [
"SetMaxAutoExpireResponseMaps",
"sets",
"the",
"max",
"outstanding",
"auto",
"expire",
"response",
"maps",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L394-L398 |
164,246 | nats-io/gnatsd | server/accounts.go | AutoExpireTTL | func (a *Account) AutoExpireTTL() time.Duration {
a.mu.RLock()
defer a.mu.RUnlock()
return a.maxaettl
} | go | func (a *Account) AutoExpireTTL() time.Duration {
a.mu.RLock()
defer a.mu.RUnlock()
return a.maxaettl
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"AutoExpireTTL",
"(",
")",
"time",
".",
"Duration",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"a",
".",
"maxaettl",
"\n",
"}"
] | // AutoExpireTTL returns the ttl for response maps. | [
"AutoExpireTTL",
"returns",
"the",
"ttl",
"for",
"response",
"maps",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L401-L405 |
164,247 | nats-io/gnatsd | server/accounts.go | SetAutoExpireTTL | func (a *Account) SetAutoExpireTTL(ttl time.Duration) {
a.mu.Lock()
defer a.mu.Unlock()
a.maxaettl = ttl
} | go | func (a *Account) SetAutoExpireTTL(ttl time.Duration) {
a.mu.Lock()
defer a.mu.Unlock()
a.maxaettl = ttl
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"SetAutoExpireTTL",
"(",
"ttl",
"time",
".",
"Duration",
")",
"{",
"a",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"a",
".",
"maxaettl",
"=",
"ttl",
"\n... | // SetAutoExpireTTL sets the ttl for response maps. | [
"SetAutoExpireTTL",
"sets",
"the",
"ttl",
"for",
"response",
"maps",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L408-L412 |
164,248 | nats-io/gnatsd | server/accounts.go | autoExpireResponseMaps | func (a *Account) autoExpireResponseMaps() []*serviceImport {
a.mu.RLock()
defer a.mu.RUnlock()
if len(a.imports.services) == 0 {
return nil
}
aesis := make([]*serviceImport, 0, len(a.imports.services))
for _, si := range a.imports.services {
if si.ae {
aesis = append(aesis, si)
}
}
sort.Slice(aesis, func(i, j int) bool {
return aesis[i].ts < aesis[j].ts
})
return aesis
} | go | func (a *Account) autoExpireResponseMaps() []*serviceImport {
a.mu.RLock()
defer a.mu.RUnlock()
if len(a.imports.services) == 0 {
return nil
}
aesis := make([]*serviceImport, 0, len(a.imports.services))
for _, si := range a.imports.services {
if si.ae {
aesis = append(aesis, si)
}
}
sort.Slice(aesis, func(i, j int) bool {
return aesis[i].ts < aesis[j].ts
})
return aesis
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"autoExpireResponseMaps",
"(",
")",
"[",
"]",
"*",
"serviceImport",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"len",
"(",
"a",
".",
"... | // Return a list of the current autoExpireResponseMaps. | [
"Return",
"a",
"list",
"of",
"the",
"current",
"autoExpireResponseMaps",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L415-L431 |
164,249 | nats-io/gnatsd | server/accounts.go | addImplicitServiceImport | func (a *Account) addImplicitServiceImport(destination *Account, from, to string, autoexpire bool, claim *jwt.Import) error {
a.mu.Lock()
if a.imports.services == nil {
a.imports.services = make(map[string]*serviceImport)
}
si := &serviceImport{destination, from, to, autoexpire, 0, claim, false}
a.imports.services[from] = si
if autoexpire {
a.nae++
si.ts = time.Now().Unix()
if a.nae > a.maxnae && !a.pruning {
a.pruning = true
go a.pruneAutoExpireResponseMaps()
}
}
a.mu.Unlock()
return nil
} | go | func (a *Account) addImplicitServiceImport(destination *Account, from, to string, autoexpire bool, claim *jwt.Import) error {
a.mu.Lock()
if a.imports.services == nil {
a.imports.services = make(map[string]*serviceImport)
}
si := &serviceImport{destination, from, to, autoexpire, 0, claim, false}
a.imports.services[from] = si
if autoexpire {
a.nae++
si.ts = time.Now().Unix()
if a.nae > a.maxnae && !a.pruning {
a.pruning = true
go a.pruneAutoExpireResponseMaps()
}
}
a.mu.Unlock()
return nil
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"addImplicitServiceImport",
"(",
"destination",
"*",
"Account",
",",
"from",
",",
"to",
"string",
",",
"autoexpire",
"bool",
",",
"claim",
"*",
"jwt",
".",
"Import",
")",
"error",
"{",
"a",
".",
"mu",
".",
"Lock",... | // Add a route to connect from an implicit route created for a response to a request.
// This does no checks and should be only called by the msg processing code. Use
// addServiceImport from above if responding to user input or config changes, etc. | [
"Add",
"a",
"route",
"to",
"connect",
"from",
"an",
"implicit",
"route",
"created",
"for",
"a",
"response",
"to",
"a",
"request",
".",
"This",
"does",
"no",
"checks",
"and",
"should",
"be",
"only",
"called",
"by",
"the",
"msg",
"processing",
"code",
".",... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L436-L453 |
164,250 | nats-io/gnatsd | server/accounts.go | pruneAutoExpireResponseMaps | func (a *Account) pruneAutoExpireResponseMaps() {
defer func() {
a.mu.Lock()
a.pruning = false
a.mu.Unlock()
}()
a.mu.RLock()
ttl := int64(a.maxaettl/time.Second) + 1
a.mu.RUnlock()
for {
sis := a.autoExpireResponseMaps()
// Check ttl items.
now := time.Now().Unix()
for i, si := range sis {
if now-si.ts >= ttl {
a.removeServiceImport(si.from)
} else {
sis = sis[i:]
break
}
}
a.mu.RLock()
numOver := int(a.nae - a.maxnae)
a.mu.RUnlock()
if numOver <= 0 {
return
} else if numOver >= len(sis) {
numOver = len(sis) - 1
}
// These are in sorted order, remove at least numOver
for _, si := range sis[:numOver] {
a.removeServiceImport(si.from)
}
}
} | go | func (a *Account) pruneAutoExpireResponseMaps() {
defer func() {
a.mu.Lock()
a.pruning = false
a.mu.Unlock()
}()
a.mu.RLock()
ttl := int64(a.maxaettl/time.Second) + 1
a.mu.RUnlock()
for {
sis := a.autoExpireResponseMaps()
// Check ttl items.
now := time.Now().Unix()
for i, si := range sis {
if now-si.ts >= ttl {
a.removeServiceImport(si.from)
} else {
sis = sis[i:]
break
}
}
a.mu.RLock()
numOver := int(a.nae - a.maxnae)
a.mu.RUnlock()
if numOver <= 0 {
return
} else if numOver >= len(sis) {
numOver = len(sis) - 1
}
// These are in sorted order, remove at least numOver
for _, si := range sis[:numOver] {
a.removeServiceImport(si.from)
}
}
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"pruneAutoExpireResponseMaps",
"(",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"a",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"a",
".",
"pruning",
"=",
"false",
"\n",
"a",
".",
"mu",
".",
"Unlock",
"(",
")",
... | // This will prune the list to below the threshold and remove all ttl'd maps. | [
"This",
"will",
"prune",
"the",
"list",
"to",
"below",
"the",
"threshold",
"and",
"remove",
"all",
"ttl",
"d",
"maps",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L456-L495 |
164,251 | nats-io/gnatsd | server/accounts.go | AddStreamImportWithClaim | func (a *Account) AddStreamImportWithClaim(account *Account, from, prefix string, imClaim *jwt.Import) error {
if account == nil {
return ErrMissingAccount
}
// First check to see if the account has authorized export of the subject.
if !account.checkStreamImportAuthorized(a, from, imClaim) {
return ErrStreamImportAuthorization
}
a.mu.Lock()
defer a.mu.Unlock()
if a.imports.streams == nil {
a.imports.streams = make(map[string]*streamImport)
}
if prefix != "" && prefix[len(prefix)-1] != btsep {
prefix = prefix + string(btsep)
}
// TODO(dlc) - collisions, etc.
a.imports.streams[from] = &streamImport{account, from, prefix, imClaim, false}
return nil
} | go | func (a *Account) AddStreamImportWithClaim(account *Account, from, prefix string, imClaim *jwt.Import) error {
if account == nil {
return ErrMissingAccount
}
// First check to see if the account has authorized export of the subject.
if !account.checkStreamImportAuthorized(a, from, imClaim) {
return ErrStreamImportAuthorization
}
a.mu.Lock()
defer a.mu.Unlock()
if a.imports.streams == nil {
a.imports.streams = make(map[string]*streamImport)
}
if prefix != "" && prefix[len(prefix)-1] != btsep {
prefix = prefix + string(btsep)
}
// TODO(dlc) - collisions, etc.
a.imports.streams[from] = &streamImport{account, from, prefix, imClaim, false}
return nil
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"AddStreamImportWithClaim",
"(",
"account",
"*",
"Account",
",",
"from",
",",
"prefix",
"string",
",",
"imClaim",
"*",
"jwt",
".",
"Import",
")",
"error",
"{",
"if",
"account",
"==",
"nil",
"{",
"return",
"ErrMissin... | // AddStreamImportWithClaim will add in the stream import from a specific account with optional token. | [
"AddStreamImportWithClaim",
"will",
"add",
"in",
"the",
"stream",
"import",
"from",
"a",
"specific",
"account",
"with",
"optional",
"token",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L498-L519 |
164,252 | nats-io/gnatsd | server/accounts.go | AddStreamImport | func (a *Account) AddStreamImport(account *Account, from, prefix string) error {
return a.AddStreamImportWithClaim(account, from, prefix, nil)
} | go | func (a *Account) AddStreamImport(account *Account, from, prefix string) error {
return a.AddStreamImportWithClaim(account, from, prefix, nil)
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"AddStreamImport",
"(",
"account",
"*",
"Account",
",",
"from",
",",
"prefix",
"string",
")",
"error",
"{",
"return",
"a",
".",
"AddStreamImportWithClaim",
"(",
"account",
",",
"from",
",",
"prefix",
",",
"nil",
")"... | // AddStreamImport will add in the stream import from a specific account. | [
"AddStreamImport",
"will",
"add",
"in",
"the",
"stream",
"import",
"from",
"a",
"specific",
"account",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L522-L524 |
164,253 | nats-io/gnatsd | server/accounts.go | AddStreamExport | func (a *Account) AddStreamExport(subject string, accounts []*Account) error {
a.mu.Lock()
defer a.mu.Unlock()
if a == nil {
return ErrMissingAccount
}
if a.exports.streams == nil {
a.exports.streams = make(map[string]*exportAuth)
}
ea := a.exports.streams[subject]
if accounts != nil {
if ea == nil {
ea = &exportAuth{}
}
// empty means auth required but will be import token.
if len(accounts) == 0 {
ea.tokenReq = true
} else {
if ea.approved == nil {
ea.approved = make(map[string]*Account, len(accounts))
}
for _, acc := range accounts {
ea.approved[acc.Name] = acc
}
}
}
a.exports.streams[subject] = ea
return nil
} | go | func (a *Account) AddStreamExport(subject string, accounts []*Account) error {
a.mu.Lock()
defer a.mu.Unlock()
if a == nil {
return ErrMissingAccount
}
if a.exports.streams == nil {
a.exports.streams = make(map[string]*exportAuth)
}
ea := a.exports.streams[subject]
if accounts != nil {
if ea == nil {
ea = &exportAuth{}
}
// empty means auth required but will be import token.
if len(accounts) == 0 {
ea.tokenReq = true
} else {
if ea.approved == nil {
ea.approved = make(map[string]*Account, len(accounts))
}
for _, acc := range accounts {
ea.approved[acc.Name] = acc
}
}
}
a.exports.streams[subject] = ea
return nil
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"AddStreamExport",
"(",
"subject",
"string",
",",
"accounts",
"[",
"]",
"*",
"Account",
")",
"error",
"{",
"a",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",... | // AddStreamExport will add an export to the account. If accounts is nil
// it will signify a public export, meaning anyone can impoort. | [
"AddStreamExport",
"will",
"add",
"an",
"export",
"to",
"the",
"account",
".",
"If",
"accounts",
"is",
"nil",
"it",
"will",
"signify",
"a",
"public",
"export",
"meaning",
"anyone",
"can",
"impoort",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L531-L559 |
164,254 | nats-io/gnatsd | server/accounts.go | checkStreamImportAuthorized | func (a *Account) checkStreamImportAuthorized(account *Account, subject string, imClaim *jwt.Import) bool {
// Find the subject in the exports list.
a.mu.RLock()
defer a.mu.RUnlock()
return a.checkStreamImportAuthorizedNoLock(account, subject, imClaim)
} | go | func (a *Account) checkStreamImportAuthorized(account *Account, subject string, imClaim *jwt.Import) bool {
// Find the subject in the exports list.
a.mu.RLock()
defer a.mu.RUnlock()
return a.checkStreamImportAuthorizedNoLock(account, subject, imClaim)
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"checkStreamImportAuthorized",
"(",
"account",
"*",
"Account",
",",
"subject",
"string",
",",
"imClaim",
"*",
"jwt",
".",
"Import",
")",
"bool",
"{",
"// Find the subject in the exports list.",
"a",
".",
"mu",
".",
"RLock... | // Check if another account is authorized to import from us. | [
"Check",
"if",
"another",
"account",
"is",
"authorized",
"to",
"import",
"from",
"us",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L562-L567 |
164,255 | nats-io/gnatsd | server/accounts.go | fetchActivation | func fetchActivation(url string) string {
// FIXME(dlc) - Make configurable.
c := &http.Client{Timeout: 2 * time.Second}
resp, err := c.Get(url)
if err != nil || resp == nil {
return ""
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ""
}
return string(body)
} | go | func fetchActivation(url string) string {
// FIXME(dlc) - Make configurable.
c := &http.Client{Timeout: 2 * time.Second}
resp, err := c.Get(url)
if err != nil || resp == nil {
return ""
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ""
}
return string(body)
} | [
"func",
"fetchActivation",
"(",
"url",
"string",
")",
"string",
"{",
"// FIXME(dlc) - Make configurable.",
"c",
":=",
"&",
"http",
".",
"Client",
"{",
"Timeout",
":",
"2",
"*",
"time",
".",
"Second",
"}",
"\n",
"resp",
",",
"err",
":=",
"c",
".",
"Get",
... | // Will fetch the activation token for an import. | [
"Will",
"fetch",
"the",
"activation",
"token",
"for",
"an",
"import",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L614-L627 |
164,256 | nats-io/gnatsd | server/accounts.go | streamActivationExpired | func (a *Account) streamActivationExpired(subject string) {
a.mu.RLock()
if a.expired || a.imports.streams == nil {
a.mu.RUnlock()
return
}
si := a.imports.streams[subject]
if si == nil || si.invalid {
a.mu.RUnlock()
return
}
a.mu.RUnlock()
if si.acc.checkActivation(a, si.claim, false) {
// The token has been updated most likely and we are good to go.
return
}
a.mu.Lock()
si.invalid = true
clients := make([]*client, 0, len(a.clients))
for _, c := range a.clients {
clients = append(clients, c)
}
awcsti := map[string]struct{}{a.Name: struct{}{}}
a.mu.Unlock()
for _, c := range clients {
c.processSubsOnConfigReload(awcsti)
}
} | go | func (a *Account) streamActivationExpired(subject string) {
a.mu.RLock()
if a.expired || a.imports.streams == nil {
a.mu.RUnlock()
return
}
si := a.imports.streams[subject]
if si == nil || si.invalid {
a.mu.RUnlock()
return
}
a.mu.RUnlock()
if si.acc.checkActivation(a, si.claim, false) {
// The token has been updated most likely and we are good to go.
return
}
a.mu.Lock()
si.invalid = true
clients := make([]*client, 0, len(a.clients))
for _, c := range a.clients {
clients = append(clients, c)
}
awcsti := map[string]struct{}{a.Name: struct{}{}}
a.mu.Unlock()
for _, c := range clients {
c.processSubsOnConfigReload(awcsti)
}
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"streamActivationExpired",
"(",
"subject",
"string",
")",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"if",
"a",
".",
"expired",
"||",
"a",
".",
"imports",
".",
"streams",
"==",
"nil",
"{",
"a",
".",
... | // These are import stream specific versions for when an activation expires. | [
"These",
"are",
"import",
"stream",
"specific",
"versions",
"for",
"when",
"an",
"activation",
"expires",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L630-L659 |
164,257 | nats-io/gnatsd | server/accounts.go | serviceActivationExpired | func (a *Account) serviceActivationExpired(subject string) {
a.mu.RLock()
if a.expired || a.imports.services == nil {
a.mu.RUnlock()
return
}
si := a.imports.services[subject]
if si == nil || si.invalid {
a.mu.RUnlock()
return
}
a.mu.RUnlock()
if si.acc.checkActivation(a, si.claim, false) {
// The token has been updated most likely and we are good to go.
return
}
a.mu.Lock()
si.invalid = true
a.mu.Unlock()
} | go | func (a *Account) serviceActivationExpired(subject string) {
a.mu.RLock()
if a.expired || a.imports.services == nil {
a.mu.RUnlock()
return
}
si := a.imports.services[subject]
if si == nil || si.invalid {
a.mu.RUnlock()
return
}
a.mu.RUnlock()
if si.acc.checkActivation(a, si.claim, false) {
// The token has been updated most likely and we are good to go.
return
}
a.mu.Lock()
si.invalid = true
a.mu.Unlock()
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"serviceActivationExpired",
"(",
"subject",
"string",
")",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"if",
"a",
".",
"expired",
"||",
"a",
".",
"imports",
".",
"services",
"==",
"nil",
"{",
"a",
".",
... | // These are import service specific versions for when an activation expires. | [
"These",
"are",
"import",
"service",
"specific",
"versions",
"for",
"when",
"an",
"activation",
"expires",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L662-L683 |
164,258 | nats-io/gnatsd | server/accounts.go | activationExpired | func (a *Account) activationExpired(subject string, kind jwt.ExportType) {
switch kind {
case jwt.Stream:
a.streamActivationExpired(subject)
case jwt.Service:
a.serviceActivationExpired(subject)
}
} | go | func (a *Account) activationExpired(subject string, kind jwt.ExportType) {
switch kind {
case jwt.Stream:
a.streamActivationExpired(subject)
case jwt.Service:
a.serviceActivationExpired(subject)
}
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"activationExpired",
"(",
"subject",
"string",
",",
"kind",
"jwt",
".",
"ExportType",
")",
"{",
"switch",
"kind",
"{",
"case",
"jwt",
".",
"Stream",
":",
"a",
".",
"streamActivationExpired",
"(",
"subject",
")",
"\n... | // Fires for expired activation tokens. We could track this with timers etc.
// Instead we just re-analyze where we are and if we need to act. | [
"Fires",
"for",
"expired",
"activation",
"tokens",
".",
"We",
"could",
"track",
"this",
"with",
"timers",
"etc",
".",
"Instead",
"we",
"just",
"re",
"-",
"analyze",
"where",
"we",
"are",
"and",
"if",
"we",
"need",
"to",
"act",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L687-L694 |
164,259 | nats-io/gnatsd | server/accounts.go | checkActivation | func (a *Account) checkActivation(acc *Account, claim *jwt.Import, expTimer bool) bool {
if claim == nil || claim.Token == "" {
return false
}
// Create a quick clone so we can inline Token JWT.
clone := *claim
// We grab the token from a URL by hand here since we need expiration etc.
if url, err := url.Parse(clone.Token); err == nil && url.Scheme != "" {
clone.Token = fetchActivation(url.String())
}
vr := jwt.CreateValidationResults()
clone.Validate(a.Name, vr)
if vr.IsBlocking(true) {
return false
}
act, err := jwt.DecodeActivationClaims(clone.Token)
if err != nil {
return false
}
vr = jwt.CreateValidationResults()
act.Validate(vr)
if vr.IsBlocking(true) {
return false
}
if !a.isIssuerClaimTrusted(act) {
return false
}
if act.Expires != 0 {
tn := time.Now().Unix()
if act.Expires <= tn {
return false
}
if expTimer {
expiresAt := time.Duration(act.Expires - tn)
time.AfterFunc(expiresAt*time.Second, func() {
acc.activationExpired(string(act.ImportSubject), claim.Type)
})
}
}
return true
} | go | func (a *Account) checkActivation(acc *Account, claim *jwt.Import, expTimer bool) bool {
if claim == nil || claim.Token == "" {
return false
}
// Create a quick clone so we can inline Token JWT.
clone := *claim
// We grab the token from a URL by hand here since we need expiration etc.
if url, err := url.Parse(clone.Token); err == nil && url.Scheme != "" {
clone.Token = fetchActivation(url.String())
}
vr := jwt.CreateValidationResults()
clone.Validate(a.Name, vr)
if vr.IsBlocking(true) {
return false
}
act, err := jwt.DecodeActivationClaims(clone.Token)
if err != nil {
return false
}
vr = jwt.CreateValidationResults()
act.Validate(vr)
if vr.IsBlocking(true) {
return false
}
if !a.isIssuerClaimTrusted(act) {
return false
}
if act.Expires != 0 {
tn := time.Now().Unix()
if act.Expires <= tn {
return false
}
if expTimer {
expiresAt := time.Duration(act.Expires - tn)
time.AfterFunc(expiresAt*time.Second, func() {
acc.activationExpired(string(act.ImportSubject), claim.Type)
})
}
}
return true
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"checkActivation",
"(",
"acc",
"*",
"Account",
",",
"claim",
"*",
"jwt",
".",
"Import",
",",
"expTimer",
"bool",
")",
"bool",
"{",
"if",
"claim",
"==",
"nil",
"||",
"claim",
".",
"Token",
"==",
"\"",
"\"",
"{"... | // checkActivation will check the activation token for validity. | [
"checkActivation",
"will",
"check",
"the",
"activation",
"token",
"for",
"validity",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L697-L739 |
164,260 | nats-io/gnatsd | server/accounts.go | isIssuerClaimTrusted | func (a *Account) isIssuerClaimTrusted(claims *jwt.ActivationClaims) bool {
// if no issuer account, issuer is the account
if claims.IssuerAccount == "" {
return true
}
// get the referenced account
if a.srv != nil {
ia, err := a.srv.lookupAccount(claims.IssuerAccount)
if err != nil {
return false
}
return ia.hasIssuer(claims.Issuer)
}
// couldn't verify
return false
} | go | func (a *Account) isIssuerClaimTrusted(claims *jwt.ActivationClaims) bool {
// if no issuer account, issuer is the account
if claims.IssuerAccount == "" {
return true
}
// get the referenced account
if a.srv != nil {
ia, err := a.srv.lookupAccount(claims.IssuerAccount)
if err != nil {
return false
}
return ia.hasIssuer(claims.Issuer)
}
// couldn't verify
return false
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"isIssuerClaimTrusted",
"(",
"claims",
"*",
"jwt",
".",
"ActivationClaims",
")",
"bool",
"{",
"// if no issuer account, issuer is the account",
"if",
"claims",
".",
"IssuerAccount",
"==",
"\"",
"\"",
"{",
"return",
"true",
... | // Returns true if the activation claim is trusted. That is the issuer matches
// the account or is an entry in the signing keys. | [
"Returns",
"true",
"if",
"the",
"activation",
"claim",
"is",
"trusted",
".",
"That",
"is",
"the",
"issuer",
"matches",
"the",
"account",
"or",
"is",
"an",
"entry",
"in",
"the",
"signing",
"keys",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L743-L758 |
164,261 | nats-io/gnatsd | server/accounts.go | checkStreamImportsEqual | func (a *Account) checkStreamImportsEqual(b *Account) bool {
if len(a.imports.streams) != len(b.imports.streams) {
return false
}
for subj, aim := range a.imports.streams {
bim := b.imports.streams[subj]
if bim == nil {
return false
}
if aim.acc.Name != bim.acc.Name || aim.from != bim.from || aim.prefix != bim.prefix {
return false
}
}
return true
} | go | func (a *Account) checkStreamImportsEqual(b *Account) bool {
if len(a.imports.streams) != len(b.imports.streams) {
return false
}
for subj, aim := range a.imports.streams {
bim := b.imports.streams[subj]
if bim == nil {
return false
}
if aim.acc.Name != bim.acc.Name || aim.from != bim.from || aim.prefix != bim.prefix {
return false
}
}
return true
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"checkStreamImportsEqual",
"(",
"b",
"*",
"Account",
")",
"bool",
"{",
"if",
"len",
"(",
"a",
".",
"imports",
".",
"streams",
")",
"!=",
"len",
"(",
"b",
".",
"imports",
".",
"streams",
")",
"{",
"return",
"fa... | // Returns true if `a` and `b` stream imports are the same. Note that the
// check is done with the account's name, not the pointer. This is used
// during config reload where we are comparing current and new config
// in which pointers are different.
// No lock is acquired in this function, so it is assumed that the
// import maps are not changed while this executes. | [
"Returns",
"true",
"if",
"a",
"and",
"b",
"stream",
"imports",
"are",
"the",
"same",
".",
"Note",
"that",
"the",
"check",
"is",
"done",
"with",
"the",
"account",
"s",
"name",
"not",
"the",
"pointer",
".",
"This",
"is",
"used",
"during",
"config",
"relo... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L766-L780 |
164,262 | nats-io/gnatsd | server/accounts.go | checkServiceImportAuthorizedNoLock | func (a *Account) checkServiceImportAuthorizedNoLock(account *Account, subject string, imClaim *jwt.Import) bool {
// Find the subject in the services list.
if a.exports.services == nil || !IsValidLiteralSubject(subject) {
return false
}
return a.checkExportApproved(account, subject, imClaim, a.exports.services)
} | go | func (a *Account) checkServiceImportAuthorizedNoLock(account *Account, subject string, imClaim *jwt.Import) bool {
// Find the subject in the services list.
if a.exports.services == nil || !IsValidLiteralSubject(subject) {
return false
}
return a.checkExportApproved(account, subject, imClaim, a.exports.services)
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"checkServiceImportAuthorizedNoLock",
"(",
"account",
"*",
"Account",
",",
"subject",
"string",
",",
"imClaim",
"*",
"jwt",
".",
"Import",
")",
"bool",
"{",
"// Find the subject in the services list.",
"if",
"a",
".",
"expo... | // Check if another account is authorized to route requests to this service. | [
"Check",
"if",
"another",
"account",
"is",
"authorized",
"to",
"route",
"requests",
"to",
"this",
"service",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L821-L827 |
164,263 | nats-io/gnatsd | server/accounts.go | IsExpired | func (a *Account) IsExpired() bool {
a.mu.RLock()
exp := a.expired
a.mu.RUnlock()
return exp
} | go | func (a *Account) IsExpired() bool {
a.mu.RLock()
exp := a.expired
a.mu.RUnlock()
return exp
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"IsExpired",
"(",
")",
"bool",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"exp",
":=",
"a",
".",
"expired",
"\n",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"exp",
"\n",
"}"
] | // IsExpired returns expiration status. | [
"IsExpired",
"returns",
"expiration",
"status",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L830-L835 |
164,264 | nats-io/gnatsd | server/accounts.go | expiredTimeout | func (a *Account) expiredTimeout() {
// Collect the clients.
a.mu.Lock()
a.expired = true
a.mu.Unlock()
cs := make([]*client, 0, len(a.clients))
a.mu.RLock()
for c := range a.clients {
cs = append(cs, c)
}
a.mu.RUnlock()
for _, c := range cs {
c.accountAuthExpired()
}
} | go | func (a *Account) expiredTimeout() {
// Collect the clients.
a.mu.Lock()
a.expired = true
a.mu.Unlock()
cs := make([]*client, 0, len(a.clients))
a.mu.RLock()
for c := range a.clients {
cs = append(cs, c)
}
a.mu.RUnlock()
for _, c := range cs {
c.accountAuthExpired()
}
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"expiredTimeout",
"(",
")",
"{",
"// Collect the clients.",
"a",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"a",
".",
"expired",
"=",
"true",
"\n",
"a",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"cs",
":=",
"... | // Called when an account has expired. | [
"Called",
"when",
"an",
"account",
"has",
"expired",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L838-L854 |
164,265 | nats-io/gnatsd | server/accounts.go | setExpirationTimer | func (a *Account) setExpirationTimer(d time.Duration) {
a.etmr = time.AfterFunc(d, a.expiredTimeout)
} | go | func (a *Account) setExpirationTimer(d time.Duration) {
a.etmr = time.AfterFunc(d, a.expiredTimeout)
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"setExpirationTimer",
"(",
"d",
"time",
".",
"Duration",
")",
"{",
"a",
".",
"etmr",
"=",
"time",
".",
"AfterFunc",
"(",
"d",
",",
"a",
".",
"expiredTimeout",
")",
"\n",
"}"
] | // Sets the expiration timer for an account JWT that has it set. | [
"Sets",
"the",
"expiration",
"timer",
"for",
"an",
"account",
"JWT",
"that",
"has",
"it",
"set",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L857-L859 |
164,266 | nats-io/gnatsd | server/accounts.go | checkExpiration | func (a *Account) checkExpiration(claims *jwt.ClaimsData) {
a.mu.Lock()
defer a.mu.Unlock()
a.clearExpirationTimer()
if claims.Expires == 0 {
a.expired = false
return
}
tn := time.Now().Unix()
if claims.Expires <= tn {
a.expired = true
return
}
expiresAt := time.Duration(claims.Expires - tn)
a.setExpirationTimer(expiresAt * time.Second)
a.expired = false
} | go | func (a *Account) checkExpiration(claims *jwt.ClaimsData) {
a.mu.Lock()
defer a.mu.Unlock()
a.clearExpirationTimer()
if claims.Expires == 0 {
a.expired = false
return
}
tn := time.Now().Unix()
if claims.Expires <= tn {
a.expired = true
return
}
expiresAt := time.Duration(claims.Expires - tn)
a.setExpirationTimer(expiresAt * time.Second)
a.expired = false
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"checkExpiration",
"(",
"claims",
"*",
"jwt",
".",
"ClaimsData",
")",
"{",
"a",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"a",
".",
"clearExpirationTimer... | // Check expiration and set the proper state as needed. | [
"Check",
"expiration",
"and",
"set",
"the",
"proper",
"state",
"as",
"needed",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L872-L889 |
164,267 | nats-io/gnatsd | server/accounts.go | hasIssuer | func (a *Account) hasIssuer(issuer string) bool {
a.mu.RLock()
defer a.mu.RUnlock()
// same issuer
if a.Issuer == issuer {
return true
}
for i := 0; i < len(a.signingKeys); i++ {
if a.signingKeys[i] == issuer {
return true
}
}
return false
} | go | func (a *Account) hasIssuer(issuer string) bool {
a.mu.RLock()
defer a.mu.RUnlock()
// same issuer
if a.Issuer == issuer {
return true
}
for i := 0; i < len(a.signingKeys); i++ {
if a.signingKeys[i] == issuer {
return true
}
}
return false
} | [
"func",
"(",
"a",
"*",
"Account",
")",
"hasIssuer",
"(",
"issuer",
"string",
")",
"bool",
"{",
"a",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"a",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"// same issuer",
"if",
"a",
".",
"Issuer",
"=="... | // hasIssuer returns true if the issuer matches the account
// issuer or it is a signing key for the account. | [
"hasIssuer",
"returns",
"true",
"if",
"the",
"issuer",
"matches",
"the",
"account",
"issuer",
"or",
"it",
"is",
"a",
"signing",
"key",
"for",
"the",
"account",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L893-L906 |
164,268 | nats-io/gnatsd | server/accounts.go | SetAccountResolver | func (s *Server) SetAccountResolver(ar AccountResolver) {
s.mu.Lock()
s.accResolver = ar
s.mu.Unlock()
} | go | func (s *Server) SetAccountResolver(ar AccountResolver) {
s.mu.Lock()
s.accResolver = ar
s.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"SetAccountResolver",
"(",
"ar",
"AccountResolver",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"accResolver",
"=",
"ar",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // SetAccountResolver will assign the account resolver. | [
"SetAccountResolver",
"will",
"assign",
"the",
"account",
"resolver",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L919-L923 |
164,269 | nats-io/gnatsd | server/accounts.go | AccountResolver | func (s *Server) AccountResolver() AccountResolver {
s.mu.Lock()
defer s.mu.Unlock()
return s.accResolver
} | go | func (s *Server) AccountResolver() AccountResolver {
s.mu.Lock()
defer s.mu.Unlock()
return s.accResolver
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"AccountResolver",
"(",
")",
"AccountResolver",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"s",
".",
"accResolver",
"\n",
"}"
] | // AccountResolver returns the registered account resolver. | [
"AccountResolver",
"returns",
"the",
"registered",
"account",
"resolver",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L926-L930 |
164,270 | nats-io/gnatsd | server/accounts.go | UpdateAccountClaims | func (s *Server) UpdateAccountClaims(a *Account, ac *jwt.AccountClaims) {
s.updateAccountClaims(a, ac)
} | go | func (s *Server) UpdateAccountClaims(a *Account, ac *jwt.AccountClaims) {
s.updateAccountClaims(a, ac)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"UpdateAccountClaims",
"(",
"a",
"*",
"Account",
",",
"ac",
"*",
"jwt",
".",
"AccountClaims",
")",
"{",
"s",
".",
"updateAccountClaims",
"(",
"a",
",",
"ac",
")",
"\n",
"}"
] | // UpdateAccountClaims will call updateAccountClaims. | [
"UpdateAccountClaims",
"will",
"call",
"updateAccountClaims",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L933-L935 |
164,271 | nats-io/gnatsd | server/accounts.go | buildInternalAccount | func (s *Server) buildInternalAccount(ac *jwt.AccountClaims) *Account {
acc := NewAccount(ac.Subject)
acc.Issuer = ac.Issuer
s.updateAccountClaims(acc, ac)
return acc
} | go | func (s *Server) buildInternalAccount(ac *jwt.AccountClaims) *Account {
acc := NewAccount(ac.Subject)
acc.Issuer = ac.Issuer
s.updateAccountClaims(acc, ac)
return acc
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"buildInternalAccount",
"(",
"ac",
"*",
"jwt",
".",
"AccountClaims",
")",
"*",
"Account",
"{",
"acc",
":=",
"NewAccount",
"(",
"ac",
".",
"Subject",
")",
"\n",
"acc",
".",
"Issuer",
"=",
"ac",
".",
"Issuer",
"\n"... | // Helper to build an internal account structure from a jwt.AccountClaims. | [
"Helper",
"to",
"build",
"an",
"internal",
"account",
"structure",
"from",
"a",
"jwt",
".",
"AccountClaims",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L1110-L1115 |
164,272 | nats-io/gnatsd | server/accounts.go | buildInternalNkeyUser | func buildInternalNkeyUser(uc *jwt.UserClaims, acc *Account) *NkeyUser {
nu := &NkeyUser{Nkey: uc.Subject, Account: acc}
if uc.IssuerAccount != "" {
nu.SigningKey = uc.Issuer
}
// Now check for permissions.
var p *Permissions
if len(uc.Pub.Allow) > 0 || len(uc.Pub.Deny) > 0 {
if p == nil {
p = &Permissions{}
}
p.Publish = &SubjectPermission{}
p.Publish.Allow = uc.Pub.Allow
p.Publish.Deny = uc.Pub.Deny
}
if len(uc.Sub.Allow) > 0 || len(uc.Sub.Deny) > 0 {
if p == nil {
p = &Permissions{}
}
p.Subscribe = &SubjectPermission{}
p.Subscribe.Allow = uc.Sub.Allow
p.Subscribe.Deny = uc.Sub.Deny
}
nu.Permissions = p
return nu
} | go | func buildInternalNkeyUser(uc *jwt.UserClaims, acc *Account) *NkeyUser {
nu := &NkeyUser{Nkey: uc.Subject, Account: acc}
if uc.IssuerAccount != "" {
nu.SigningKey = uc.Issuer
}
// Now check for permissions.
var p *Permissions
if len(uc.Pub.Allow) > 0 || len(uc.Pub.Deny) > 0 {
if p == nil {
p = &Permissions{}
}
p.Publish = &SubjectPermission{}
p.Publish.Allow = uc.Pub.Allow
p.Publish.Deny = uc.Pub.Deny
}
if len(uc.Sub.Allow) > 0 || len(uc.Sub.Deny) > 0 {
if p == nil {
p = &Permissions{}
}
p.Subscribe = &SubjectPermission{}
p.Subscribe.Allow = uc.Sub.Allow
p.Subscribe.Deny = uc.Sub.Deny
}
nu.Permissions = p
return nu
} | [
"func",
"buildInternalNkeyUser",
"(",
"uc",
"*",
"jwt",
".",
"UserClaims",
",",
"acc",
"*",
"Account",
")",
"*",
"NkeyUser",
"{",
"nu",
":=",
"&",
"NkeyUser",
"{",
"Nkey",
":",
"uc",
".",
"Subject",
",",
"Account",
":",
"acc",
"}",
"\n",
"if",
"uc",
... | // Helper to build internal NKeyUser. | [
"Helper",
"to",
"build",
"internal",
"NKeyUser",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L1118-L1145 |
164,273 | nats-io/gnatsd | server/accounts.go | Fetch | func (m *MemAccResolver) Fetch(name string) (string, error) {
if j, ok := m.sm.Load(name); ok {
return j.(string), nil
}
return _EMPTY_, ErrMissingAccount
} | go | func (m *MemAccResolver) Fetch(name string) (string, error) {
if j, ok := m.sm.Load(name); ok {
return j.(string), nil
}
return _EMPTY_, ErrMissingAccount
} | [
"func",
"(",
"m",
"*",
"MemAccResolver",
")",
"Fetch",
"(",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"j",
",",
"ok",
":=",
"m",
".",
"sm",
".",
"Load",
"(",
"name",
")",
";",
"ok",
"{",
"return",
"j",
".",
"(",
"str... | // Fetch will fetch the account jwt claims from the internal sync.Map. | [
"Fetch",
"will",
"fetch",
"the",
"account",
"jwt",
"claims",
"from",
"the",
"internal",
"sync",
".",
"Map",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L1159-L1164 |
164,274 | nats-io/gnatsd | server/accounts.go | Store | func (m *MemAccResolver) Store(name, jwt string) error {
m.sm.Store(name, jwt)
return nil
} | go | func (m *MemAccResolver) Store(name, jwt string) error {
m.sm.Store(name, jwt)
return nil
} | [
"func",
"(",
"m",
"*",
"MemAccResolver",
")",
"Store",
"(",
"name",
",",
"jwt",
"string",
")",
"error",
"{",
"m",
".",
"sm",
".",
"Store",
"(",
"name",
",",
"jwt",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Store will store the account jwt claims in the internal sync.Map. | [
"Store",
"will",
"store",
"the",
"account",
"jwt",
"claims",
"in",
"the",
"internal",
"sync",
".",
"Map",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L1167-L1170 |
164,275 | nats-io/gnatsd | server/accounts.go | NewURLAccResolver | func NewURLAccResolver(url string) (*URLAccResolver, error) {
if !strings.HasSuffix(url, "/") {
url += "/"
}
// Do basic test to see if anyone is home.
// FIXME(dlc) - Make timeout configurable post MVP.
ur := &URLAccResolver{
url: url,
c: &http.Client{Timeout: 2 * time.Second},
}
if _, err := ur.Fetch(""); err != nil {
return nil, err
}
return ur, nil
} | go | func NewURLAccResolver(url string) (*URLAccResolver, error) {
if !strings.HasSuffix(url, "/") {
url += "/"
}
// Do basic test to see if anyone is home.
// FIXME(dlc) - Make timeout configurable post MVP.
ur := &URLAccResolver{
url: url,
c: &http.Client{Timeout: 2 * time.Second},
}
if _, err := ur.Fetch(""); err != nil {
return nil, err
}
return ur, nil
} | [
"func",
"NewURLAccResolver",
"(",
"url",
"string",
")",
"(",
"*",
"URLAccResolver",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"url",
",",
"\"",
"\"",
")",
"{",
"url",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"// Do basic test to se... | // NewURLAccResolver returns a new resolver for the given base URL. | [
"NewURLAccResolver",
"returns",
"a",
"new",
"resolver",
"for",
"the",
"given",
"base",
"URL",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L1179-L1193 |
164,276 | nats-io/gnatsd | server/accounts.go | Fetch | func (ur *URLAccResolver) Fetch(name string) (string, error) {
url := ur.url + name
resp, err := ur.c.Get(url)
if err != nil {
return _EMPTY_, fmt.Errorf("could not fetch <%q>: %v", url, err)
} else if resp == nil {
return _EMPTY_, fmt.Errorf("could not fetch <%q>: no response", url)
} else if resp.StatusCode != http.StatusOK {
return _EMPTY_, fmt.Errorf("could not fetch <%q>: %v", url, resp.Status)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return _EMPTY_, err
}
return string(body), nil
} | go | func (ur *URLAccResolver) Fetch(name string) (string, error) {
url := ur.url + name
resp, err := ur.c.Get(url)
if err != nil {
return _EMPTY_, fmt.Errorf("could not fetch <%q>: %v", url, err)
} else if resp == nil {
return _EMPTY_, fmt.Errorf("could not fetch <%q>: no response", url)
} else if resp.StatusCode != http.StatusOK {
return _EMPTY_, fmt.Errorf("could not fetch <%q>: %v", url, resp.Status)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return _EMPTY_, err
}
return string(body), nil
} | [
"func",
"(",
"ur",
"*",
"URLAccResolver",
")",
"Fetch",
"(",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"url",
":=",
"ur",
".",
"url",
"+",
"name",
"\n",
"resp",
",",
"err",
":=",
"ur",
".",
"c",
".",
"Get",
"(",
"url",
")",
... | // Fetch will fetch the account jwt claims from the base url, appending the
// account name onto the end. | [
"Fetch",
"will",
"fetch",
"the",
"account",
"jwt",
"claims",
"from",
"the",
"base",
"url",
"appending",
"the",
"account",
"name",
"onto",
"the",
"end",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/accounts.go#L1197-L1213 |
164,277 | nats-io/gnatsd | conf/parse.go | ParseFile | func ParseFile(fp string) (map[string]interface{}, error) {
data, err := ioutil.ReadFile(fp)
if err != nil {
return nil, fmt.Errorf("error opening config file: %v", err)
}
p, err := parse(string(data), fp, false)
if err != nil {
return nil, err
}
return p.mapping, nil
} | go | func ParseFile(fp string) (map[string]interface{}, error) {
data, err := ioutil.ReadFile(fp)
if err != nil {
return nil, fmt.Errorf("error opening config file: %v", err)
}
p, err := parse(string(data), fp, false)
if err != nil {
return nil, err
}
return p.mapping, nil
} | [
"func",
"ParseFile",
"(",
"fp",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"fp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil... | // ParseFile is a helper to open file, etc. and parse the contents. | [
"ParseFile",
"is",
"a",
"helper",
"to",
"open",
"file",
"etc",
".",
"and",
"parse",
"the",
"contents",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/parse.go#L74-L85 |
164,278 | nats-io/gnatsd | conf/parse.go | ParseFileWithChecks | func ParseFileWithChecks(fp string) (map[string]interface{}, error) {
data, err := ioutil.ReadFile(fp)
if err != nil {
return nil, err
}
p, err := parse(string(data), fp, true)
if err != nil {
return nil, err
}
return p.mapping, nil
} | go | func ParseFileWithChecks(fp string) (map[string]interface{}, error) {
data, err := ioutil.ReadFile(fp)
if err != nil {
return nil, err
}
p, err := parse(string(data), fp, true)
if err != nil {
return nil, err
}
return p.mapping, nil
} | [
"func",
"ParseFileWithChecks",
"(",
"fp",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"fp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"retur... | // ParseFileWithChecks is equivalent to ParseFile but runs in pedantic mode. | [
"ParseFileWithChecks",
"is",
"equivalent",
"to",
"ParseFile",
"but",
"runs",
"in",
"pedantic",
"mode",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/parse.go#L88-L100 |
164,279 | nats-io/gnatsd | conf/parse.go | lookupVariable | func (p *parser) lookupVariable(varReference string) (interface{}, bool, error) {
// Do special check to see if it is a raw bcrypt string.
if strings.HasPrefix(varReference, bcryptPrefix) {
return "$" + varReference, true, nil
}
// Loop through contexts currently on the stack.
for i := len(p.ctxs) - 1; i >= 0; i-- {
ctx := p.ctxs[i]
// Process if it is a map context
if m, ok := ctx.(map[string]interface{}); ok {
if v, ok := m[varReference]; ok {
return v, ok, nil
}
}
}
// If we are here, we have exhausted our context maps and still not found anything.
// Parse from the environment.
if vStr, ok := os.LookupEnv(varReference); ok {
// Everything we get here will be a string value, so we need to process as a parser would.
if vmap, err := Parse(fmt.Sprintf("%s=%s", pkey, vStr)); err == nil {
v, ok := vmap[pkey]
return v, ok, nil
} else {
return nil, false, err
}
}
return nil, false, nil
} | go | func (p *parser) lookupVariable(varReference string) (interface{}, bool, error) {
// Do special check to see if it is a raw bcrypt string.
if strings.HasPrefix(varReference, bcryptPrefix) {
return "$" + varReference, true, nil
}
// Loop through contexts currently on the stack.
for i := len(p.ctxs) - 1; i >= 0; i-- {
ctx := p.ctxs[i]
// Process if it is a map context
if m, ok := ctx.(map[string]interface{}); ok {
if v, ok := m[varReference]; ok {
return v, ok, nil
}
}
}
// If we are here, we have exhausted our context maps and still not found anything.
// Parse from the environment.
if vStr, ok := os.LookupEnv(varReference); ok {
// Everything we get here will be a string value, so we need to process as a parser would.
if vmap, err := Parse(fmt.Sprintf("%s=%s", pkey, vStr)); err == nil {
v, ok := vmap[pkey]
return v, ok, nil
} else {
return nil, false, err
}
}
return nil, false, nil
} | [
"func",
"(",
"p",
"*",
"parser",
")",
"lookupVariable",
"(",
"varReference",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"bool",
",",
"error",
")",
"{",
"// Do special check to see if it is a raw bcrypt string.",
"if",
"strings",
".",
"HasPrefix",
"(",
"varR... | // lookupVariable will lookup a variable reference. It will use block scoping on keys
// it has seen before, with the top level scoping being the environment variables. We
// ignore array contexts and only process the map contexts..
//
// Returns true for ok if it finds something, similar to map. | [
"lookupVariable",
"will",
"lookup",
"a",
"variable",
"reference",
".",
"It",
"will",
"use",
"block",
"scoping",
"on",
"keys",
"it",
"has",
"seen",
"before",
"with",
"the",
"top",
"level",
"scoping",
"being",
"the",
"environment",
"variables",
".",
"We",
"ign... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/parse.go#L366-L395 |
164,280 | nats-io/gnatsd | server/sublist.go | addSubToResult | func (r *SublistResult) addSubToResult(sub *subscription) *SublistResult {
// Copy since others may have a reference.
nr := copyResult(r)
if sub.queue == nil {
nr.psubs = append(nr.psubs, sub)
} else {
if i := findQSlot(sub.queue, nr.qsubs); i >= 0 {
nr.qsubs[i] = append(nr.qsubs[i], sub)
} else {
nr.qsubs = append(nr.qsubs, []*subscription{sub})
}
}
return nr
} | go | func (r *SublistResult) addSubToResult(sub *subscription) *SublistResult {
// Copy since others may have a reference.
nr := copyResult(r)
if sub.queue == nil {
nr.psubs = append(nr.psubs, sub)
} else {
if i := findQSlot(sub.queue, nr.qsubs); i >= 0 {
nr.qsubs[i] = append(nr.qsubs[i], sub)
} else {
nr.qsubs = append(nr.qsubs, []*subscription{sub})
}
}
return nr
} | [
"func",
"(",
"r",
"*",
"SublistResult",
")",
"addSubToResult",
"(",
"sub",
"*",
"subscription",
")",
"*",
"SublistResult",
"{",
"// Copy since others may have a reference.",
"nr",
":=",
"copyResult",
"(",
"r",
")",
"\n",
"if",
"sub",
".",
"queue",
"==",
"nil",... | // Adds a new sub to an existing result. | [
"Adds",
"a",
"new",
"sub",
"to",
"an",
"existing",
"result",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L223-L236 |
164,281 | nats-io/gnatsd | server/sublist.go | addToCache | func (s *Sublist) addToCache(subject string, sub *subscription) {
if s.cache == nil {
return
}
// If literal we can direct match.
if subjectIsLiteral(subject) {
if v, ok := s.cache.Load(subject); ok {
r := v.(*SublistResult)
s.cache.Store(subject, r.addSubToResult(sub))
}
return
}
s.cache.Range(func(k, v interface{}) bool {
key := k.(string)
r := v.(*SublistResult)
if matchLiteral(key, subject) {
s.cache.Store(key, r.addSubToResult(sub))
}
return true
})
} | go | func (s *Sublist) addToCache(subject string, sub *subscription) {
if s.cache == nil {
return
}
// If literal we can direct match.
if subjectIsLiteral(subject) {
if v, ok := s.cache.Load(subject); ok {
r := v.(*SublistResult)
s.cache.Store(subject, r.addSubToResult(sub))
}
return
}
s.cache.Range(func(k, v interface{}) bool {
key := k.(string)
r := v.(*SublistResult)
if matchLiteral(key, subject) {
s.cache.Store(key, r.addSubToResult(sub))
}
return true
})
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"addToCache",
"(",
"subject",
"string",
",",
"sub",
"*",
"subscription",
")",
"{",
"if",
"s",
".",
"cache",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// If literal we can direct match.",
"if",
"subjectIsLiteral",
... | // addToCache will add the new entry to the existing cache
// entries if needed. Assumes write lock is held. | [
"addToCache",
"will",
"add",
"the",
"new",
"entry",
"to",
"the",
"existing",
"cache",
"entries",
"if",
"needed",
".",
"Assumes",
"write",
"lock",
"is",
"held",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L240-L260 |
164,282 | nats-io/gnatsd | server/sublist.go | removeFromCache | func (s *Sublist) removeFromCache(subject string, sub *subscription) {
if s.cache == nil {
return
}
// If literal we can direct match.
if subjectIsLiteral(subject) {
// Load for accounting
if _, ok := s.cache.Load(subject); ok {
s.cache.Delete(subject)
atomic.AddInt32(&s.cacheNum, -1)
}
return
}
s.cache.Range(func(k, v interface{}) bool {
key := k.(string)
if matchLiteral(key, subject) {
// Since someone else may be referecing, can't modify the list
// safely, just let it re-populate.
s.cache.Delete(key)
atomic.AddInt32(&s.cacheNum, -1)
}
return true
})
} | go | func (s *Sublist) removeFromCache(subject string, sub *subscription) {
if s.cache == nil {
return
}
// If literal we can direct match.
if subjectIsLiteral(subject) {
// Load for accounting
if _, ok := s.cache.Load(subject); ok {
s.cache.Delete(subject)
atomic.AddInt32(&s.cacheNum, -1)
}
return
}
s.cache.Range(func(k, v interface{}) bool {
key := k.(string)
if matchLiteral(key, subject) {
// Since someone else may be referecing, can't modify the list
// safely, just let it re-populate.
s.cache.Delete(key)
atomic.AddInt32(&s.cacheNum, -1)
}
return true
})
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"removeFromCache",
"(",
"subject",
"string",
",",
"sub",
"*",
"subscription",
")",
"{",
"if",
"s",
".",
"cache",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// If literal we can direct match.",
"if",
"subjectIsLiteral... | // removeFromCache will remove the sub from any active cache entries.
// Assumes write lock is held. | [
"removeFromCache",
"will",
"remove",
"the",
"sub",
"from",
"any",
"active",
"cache",
"entries",
".",
"Assumes",
"write",
"lock",
"is",
"held",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L264-L287 |
164,283 | nats-io/gnatsd | server/sublist.go | Match | func (s *Sublist) Match(subject string) *SublistResult {
atomic.AddUint64(&s.matches, 1)
// Check cache first.
if atomic.LoadInt32(&s.cacheNum) > 0 {
if r, ok := s.cache.Load(subject); ok {
atomic.AddUint64(&s.cacheHits, 1)
return r.(*SublistResult)
}
}
tsa := [32]string{}
tokens := tsa[:0]
start := 0
for i := 0; i < len(subject); i++ {
if subject[i] == btsep {
tokens = append(tokens, subject[start:i])
start = i + 1
}
}
tokens = append(tokens, subject[start:])
// FIXME(dlc) - Make shared pool between sublist and client readLoop?
result := &SublistResult{}
// Get result from the main structure and place into the shared cache.
// Hold the read lock to avoid race between match and store.
var n int32
s.RLock()
matchLevel(s.root, tokens, result)
// Check for empty result.
if len(result.psubs) == 0 && len(result.qsubs) == 0 {
result = emptyResult
}
if s.cache != nil {
s.cache.Store(subject, result)
n = atomic.AddInt32(&s.cacheNum, 1)
}
s.RUnlock()
// Reduce the cache count if we have exceeded our set maximum.
if n > slCacheMax && atomic.CompareAndSwapInt32(&s.ccSweep, 0, 1) {
go s.reduceCacheCount()
}
return result
} | go | func (s *Sublist) Match(subject string) *SublistResult {
atomic.AddUint64(&s.matches, 1)
// Check cache first.
if atomic.LoadInt32(&s.cacheNum) > 0 {
if r, ok := s.cache.Load(subject); ok {
atomic.AddUint64(&s.cacheHits, 1)
return r.(*SublistResult)
}
}
tsa := [32]string{}
tokens := tsa[:0]
start := 0
for i := 0; i < len(subject); i++ {
if subject[i] == btsep {
tokens = append(tokens, subject[start:i])
start = i + 1
}
}
tokens = append(tokens, subject[start:])
// FIXME(dlc) - Make shared pool between sublist and client readLoop?
result := &SublistResult{}
// Get result from the main structure and place into the shared cache.
// Hold the read lock to avoid race between match and store.
var n int32
s.RLock()
matchLevel(s.root, tokens, result)
// Check for empty result.
if len(result.psubs) == 0 && len(result.qsubs) == 0 {
result = emptyResult
}
if s.cache != nil {
s.cache.Store(subject, result)
n = atomic.AddInt32(&s.cacheNum, 1)
}
s.RUnlock()
// Reduce the cache count if we have exceeded our set maximum.
if n > slCacheMax && atomic.CompareAndSwapInt32(&s.ccSweep, 0, 1) {
go s.reduceCacheCount()
}
return result
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"Match",
"(",
"subject",
"string",
")",
"*",
"SublistResult",
"{",
"atomic",
".",
"AddUint64",
"(",
"&",
"s",
".",
"matches",
",",
"1",
")",
"\n\n",
"// Check cache first.",
"if",
"atomic",
".",
"LoadInt32",
"(",
... | // Match will match all entries to the literal subject.
// It will return a set of results for both normal and queue subscribers. | [
"Match",
"will",
"match",
"all",
"entries",
"to",
"the",
"literal",
"subject",
".",
"It",
"will",
"return",
"a",
"set",
"of",
"results",
"for",
"both",
"normal",
"and",
"queue",
"subscribers",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L294-L341 |
164,284 | nats-io/gnatsd | server/sublist.go | isRemoteQSub | func isRemoteQSub(sub *subscription) bool {
return sub != nil && sub.queue != nil && sub.client != nil && sub.client.kind == ROUTER
} | go | func isRemoteQSub(sub *subscription) bool {
return sub != nil && sub.queue != nil && sub.client != nil && sub.client.kind == ROUTER
} | [
"func",
"isRemoteQSub",
"(",
"sub",
"*",
"subscription",
")",
"bool",
"{",
"return",
"sub",
"!=",
"nil",
"&&",
"sub",
".",
"queue",
"!=",
"nil",
"&&",
"sub",
".",
"client",
"!=",
"nil",
"&&",
"sub",
".",
"client",
".",
"kind",
"==",
"ROUTER",
"\n",
... | // Helper function for auto-expanding remote qsubs. | [
"Helper",
"function",
"for",
"auto",
"-",
"expanding",
"remote",
"qsubs",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L358-L360 |
164,285 | nats-io/gnatsd | server/sublist.go | UpdateRemoteQSub | func (s *Sublist) UpdateRemoteQSub(sub *subscription) {
// We could search to make sure we find it, but probably not worth
// it unless we are thrashing the cache. Just remove from our L2 and update
// the genid so L1 will be flushed.
s.Lock()
s.removeFromCache(string(sub.subject), sub)
atomic.AddUint64(&s.genid, 1)
s.Unlock()
} | go | func (s *Sublist) UpdateRemoteQSub(sub *subscription) {
// We could search to make sure we find it, but probably not worth
// it unless we are thrashing the cache. Just remove from our L2 and update
// the genid so L1 will be flushed.
s.Lock()
s.removeFromCache(string(sub.subject), sub)
atomic.AddUint64(&s.genid, 1)
s.Unlock()
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"UpdateRemoteQSub",
"(",
"sub",
"*",
"subscription",
")",
"{",
"// We could search to make sure we find it, but probably not worth",
"// it unless we are thrashing the cache. Just remove from our L2 and update",
"// the genid so L1 will be flushed... | // UpdateRemoteQSub should be called when we update the weight of an existing
// remote queue sub. | [
"UpdateRemoteQSub",
"should",
"be",
"called",
"when",
"we",
"update",
"the",
"weight",
"of",
"an",
"existing",
"remote",
"queue",
"sub",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L364-L372 |
164,286 | nats-io/gnatsd | server/sublist.go | addNodeToResults | func addNodeToResults(n *node, results *SublistResult) {
// Normal subscriptions
if n.plist != nil {
results.psubs = append(results.psubs, n.plist...)
} else {
for _, psub := range n.psubs {
results.psubs = append(results.psubs, psub)
}
}
// Queue subscriptions
for qname, qr := range n.qsubs {
if len(qr) == 0 {
continue
}
// Need to find matching list in results
var i int
if i = findQSlot([]byte(qname), results.qsubs); i < 0 {
i = len(results.qsubs)
nqsub := make([]*subscription, 0, len(qr))
results.qsubs = append(results.qsubs, nqsub)
}
for _, sub := range qr {
if isRemoteQSub(sub) {
ns := atomic.LoadInt32(&sub.qw)
// Shadow these subscriptions
for n := 0; n < int(ns); n++ {
results.qsubs[i] = append(results.qsubs[i], sub)
}
} else {
results.qsubs[i] = append(results.qsubs[i], sub)
}
}
}
} | go | func addNodeToResults(n *node, results *SublistResult) {
// Normal subscriptions
if n.plist != nil {
results.psubs = append(results.psubs, n.plist...)
} else {
for _, psub := range n.psubs {
results.psubs = append(results.psubs, psub)
}
}
// Queue subscriptions
for qname, qr := range n.qsubs {
if len(qr) == 0 {
continue
}
// Need to find matching list in results
var i int
if i = findQSlot([]byte(qname), results.qsubs); i < 0 {
i = len(results.qsubs)
nqsub := make([]*subscription, 0, len(qr))
results.qsubs = append(results.qsubs, nqsub)
}
for _, sub := range qr {
if isRemoteQSub(sub) {
ns := atomic.LoadInt32(&sub.qw)
// Shadow these subscriptions
for n := 0; n < int(ns); n++ {
results.qsubs[i] = append(results.qsubs[i], sub)
}
} else {
results.qsubs[i] = append(results.qsubs[i], sub)
}
}
}
} | [
"func",
"addNodeToResults",
"(",
"n",
"*",
"node",
",",
"results",
"*",
"SublistResult",
")",
"{",
"// Normal subscriptions",
"if",
"n",
".",
"plist",
"!=",
"nil",
"{",
"results",
".",
"psubs",
"=",
"append",
"(",
"results",
".",
"psubs",
",",
"n",
".",
... | // This will add in a node's results to the total results. | [
"This",
"will",
"add",
"in",
"a",
"node",
"s",
"results",
"to",
"the",
"total",
"results",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L375-L408 |
164,287 | nats-io/gnatsd | server/sublist.go | findQSlot | func findQSlot(queue []byte, qsl [][]*subscription) int {
if queue == nil {
return -1
}
for i, qr := range qsl {
if len(qr) > 0 && bytes.Equal(queue, qr[0].queue) {
return i
}
}
return -1
} | go | func findQSlot(queue []byte, qsl [][]*subscription) int {
if queue == nil {
return -1
}
for i, qr := range qsl {
if len(qr) > 0 && bytes.Equal(queue, qr[0].queue) {
return i
}
}
return -1
} | [
"func",
"findQSlot",
"(",
"queue",
"[",
"]",
"byte",
",",
"qsl",
"[",
"]",
"[",
"]",
"*",
"subscription",
")",
"int",
"{",
"if",
"queue",
"==",
"nil",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"for",
"i",
",",
"qr",
":=",
"range",
"qsl",
"{",
... | // We do not use a map here since we want iteration to be past when
// processing publishes in L1 on client. So we need to walk sequentially
// for now. Keep an eye on this in case we start getting large number of
// different queue subscribers for the same subject. | [
"We",
"do",
"not",
"use",
"a",
"map",
"here",
"since",
"we",
"want",
"iteration",
"to",
"be",
"past",
"when",
"processing",
"publishes",
"in",
"L1",
"on",
"client",
".",
"So",
"we",
"need",
"to",
"walk",
"sequentially",
"for",
"now",
".",
"Keep",
"an",... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L414-L424 |
164,288 | nats-io/gnatsd | server/sublist.go | remove | func (s *Sublist) remove(sub *subscription, shouldLock bool) error {
subject := string(sub.subject)
tsa := [32]string{}
tokens := tsa[:0]
start := 0
for i := 0; i < len(subject); i++ {
if subject[i] == btsep {
tokens = append(tokens, subject[start:i])
start = i + 1
}
}
tokens = append(tokens, subject[start:])
if shouldLock {
s.Lock()
defer s.Unlock()
}
sfwc := false
l := s.root
var n *node
// Track levels for pruning
var lnts [32]lnt
levels := lnts[:0]
for _, t := range tokens {
lt := len(t)
if lt == 0 || sfwc {
return ErrInvalidSubject
}
if l == nil {
return ErrNotFound
}
if lt > 1 {
n = l.nodes[t]
} else {
switch t[0] {
case pwc:
n = l.pwc
case fwc:
n = l.fwc
sfwc = true
default:
n = l.nodes[t]
}
}
if n != nil {
levels = append(levels, lnt{l, n, t})
l = n.next
} else {
l = nil
}
}
if !s.removeFromNode(n, sub) {
return ErrNotFound
}
s.count--
s.removes++
for i := len(levels) - 1; i >= 0; i-- {
l, n, t := levels[i].l, levels[i].n, levels[i].t
if n.isEmpty() {
l.pruneNode(n, t)
}
}
s.removeFromCache(subject, sub)
atomic.AddUint64(&s.genid, 1)
return nil
} | go | func (s *Sublist) remove(sub *subscription, shouldLock bool) error {
subject := string(sub.subject)
tsa := [32]string{}
tokens := tsa[:0]
start := 0
for i := 0; i < len(subject); i++ {
if subject[i] == btsep {
tokens = append(tokens, subject[start:i])
start = i + 1
}
}
tokens = append(tokens, subject[start:])
if shouldLock {
s.Lock()
defer s.Unlock()
}
sfwc := false
l := s.root
var n *node
// Track levels for pruning
var lnts [32]lnt
levels := lnts[:0]
for _, t := range tokens {
lt := len(t)
if lt == 0 || sfwc {
return ErrInvalidSubject
}
if l == nil {
return ErrNotFound
}
if lt > 1 {
n = l.nodes[t]
} else {
switch t[0] {
case pwc:
n = l.pwc
case fwc:
n = l.fwc
sfwc = true
default:
n = l.nodes[t]
}
}
if n != nil {
levels = append(levels, lnt{l, n, t})
l = n.next
} else {
l = nil
}
}
if !s.removeFromNode(n, sub) {
return ErrNotFound
}
s.count--
s.removes++
for i := len(levels) - 1; i >= 0; i-- {
l, n, t := levels[i].l, levels[i].n, levels[i].t
if n.isEmpty() {
l.pruneNode(n, t)
}
}
s.removeFromCache(subject, sub)
atomic.AddUint64(&s.genid, 1)
return nil
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"remove",
"(",
"sub",
"*",
"subscription",
",",
"shouldLock",
"bool",
")",
"error",
"{",
"subject",
":=",
"string",
"(",
"sub",
".",
"subject",
")",
"\n",
"tsa",
":=",
"[",
"32",
"]",
"string",
"{",
"}",
"\n",... | // Raw low level remove, can do batches with lock held outside. | [
"Raw",
"low",
"level",
"remove",
"can",
"do",
"batches",
"with",
"lock",
"held",
"outside",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L462-L533 |
164,289 | nats-io/gnatsd | server/sublist.go | Remove | func (s *Sublist) Remove(sub *subscription) error {
return s.remove(sub, true)
} | go | func (s *Sublist) Remove(sub *subscription) error {
return s.remove(sub, true)
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"Remove",
"(",
"sub",
"*",
"subscription",
")",
"error",
"{",
"return",
"s",
".",
"remove",
"(",
"sub",
",",
"true",
")",
"\n",
"}"
] | // Remove will remove a subscription. | [
"Remove",
"will",
"remove",
"a",
"subscription",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L536-L538 |
164,290 | nats-io/gnatsd | server/sublist.go | RemoveBatch | func (s *Sublist) RemoveBatch(subs []*subscription) error {
s.Lock()
defer s.Unlock()
for _, sub := range subs {
if err := s.remove(sub, false); err != nil {
return err
}
}
return nil
} | go | func (s *Sublist) RemoveBatch(subs []*subscription) error {
s.Lock()
defer s.Unlock()
for _, sub := range subs {
if err := s.remove(sub, false); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"RemoveBatch",
"(",
"subs",
"[",
"]",
"*",
"subscription",
")",
"error",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"sub",
":=",
"range",
"subs",
... | // RemoveBatch will remove a list of subscriptions. | [
"RemoveBatch",
"will",
"remove",
"a",
"list",
"of",
"subscriptions",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L541-L551 |
164,291 | nats-io/gnatsd | server/sublist.go | RemoveAllForClient | func (s *Sublist) RemoveAllForClient(c *client) {
s.Lock()
removes := s.removes
s.removeClientSubs(s.root, c)
if s.removes != removes {
atomic.AddUint64(&s.genid, 1)
}
s.Unlock()
} | go | func (s *Sublist) RemoveAllForClient(c *client) {
s.Lock()
removes := s.removes
s.removeClientSubs(s.root, c)
if s.removes != removes {
atomic.AddUint64(&s.genid, 1)
}
s.Unlock()
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"RemoveAllForClient",
"(",
"c",
"*",
"client",
")",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"removes",
":=",
"s",
".",
"removes",
"\n",
"s",
".",
"removeClientSubs",
"(",
"s",
".",
"root",
",",
"c",
")",
"\n"... | // RemoveAllForClient will remove all subscriptions for a given client. | [
"RemoveAllForClient",
"will",
"remove",
"all",
"subscriptions",
"for",
"a",
"given",
"client",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L594-L602 |
164,292 | nats-io/gnatsd | server/sublist.go | pruneNode | func (l *level) pruneNode(n *node, t string) {
if n == nil {
return
}
if n == l.fwc {
l.fwc = nil
} else if n == l.pwc {
l.pwc = nil
} else {
delete(l.nodes, t)
}
} | go | func (l *level) pruneNode(n *node, t string) {
if n == nil {
return
}
if n == l.fwc {
l.fwc = nil
} else if n == l.pwc {
l.pwc = nil
} else {
delete(l.nodes, t)
}
} | [
"func",
"(",
"l",
"*",
"level",
")",
"pruneNode",
"(",
"n",
"*",
"node",
",",
"t",
"string",
")",
"{",
"if",
"n",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"n",
"==",
"l",
".",
"fwc",
"{",
"l",
".",
"fwc",
"=",
"nil",
"\n",
"}",
... | // pruneNode is used to prune an empty node from the tree. | [
"pruneNode",
"is",
"used",
"to",
"prune",
"an",
"empty",
"node",
"from",
"the",
"tree",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L605-L616 |
164,293 | nats-io/gnatsd | server/sublist.go | numNodes | func (l *level) numNodes() int {
num := len(l.nodes)
if l.pwc != nil {
num++
}
if l.fwc != nil {
num++
}
return num
} | go | func (l *level) numNodes() int {
num := len(l.nodes)
if l.pwc != nil {
num++
}
if l.fwc != nil {
num++
}
return num
} | [
"func",
"(",
"l",
"*",
"level",
")",
"numNodes",
"(",
")",
"int",
"{",
"num",
":=",
"len",
"(",
"l",
".",
"nodes",
")",
"\n",
"if",
"l",
".",
"pwc",
"!=",
"nil",
"{",
"num",
"++",
"\n",
"}",
"\n",
"if",
"l",
".",
"fwc",
"!=",
"nil",
"{",
... | // Return the number of nodes for the given level. | [
"Return",
"the",
"number",
"of",
"nodes",
"for",
"the",
"given",
"level",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L630-L639 |
164,294 | nats-io/gnatsd | server/sublist.go | Count | func (s *Sublist) Count() uint32 {
s.RLock()
defer s.RUnlock()
return s.count
} | go | func (s *Sublist) Count() uint32 {
s.RLock()
defer s.RUnlock()
return s.count
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"Count",
"(",
")",
"uint32",
"{",
"s",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"s",
".",
"count",
"\n",
"}"
] | // Count returns the number of subscriptions. | [
"Count",
"returns",
"the",
"number",
"of",
"subscriptions",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L669-L673 |
164,295 | nats-io/gnatsd | server/sublist.go | Stats | func (s *Sublist) Stats() *SublistStats {
s.Lock()
defer s.Unlock()
st := &SublistStats{}
st.NumSubs = s.count
st.NumCache = uint32(atomic.LoadInt32(&s.cacheNum))
st.NumInserts = s.inserts
st.NumRemoves = s.removes
st.NumMatches = atomic.LoadUint64(&s.matches)
if st.NumMatches > 0 {
st.CacheHitRate = float64(atomic.LoadUint64(&s.cacheHits)) / float64(st.NumMatches)
}
// whip through cache for fanout stats, this can be off if cache is full and doing evictions.
tot, max := 0, 0
clen := 0
s.cache.Range(func(k, v interface{}) bool {
clen++
r := v.(*SublistResult)
l := len(r.psubs) + len(r.qsubs)
tot += l
if l > max {
max = l
}
return true
})
st.MaxFanout = uint32(max)
if tot > 0 {
st.AvgFanout = float64(tot) / float64(clen)
}
return st
} | go | func (s *Sublist) Stats() *SublistStats {
s.Lock()
defer s.Unlock()
st := &SublistStats{}
st.NumSubs = s.count
st.NumCache = uint32(atomic.LoadInt32(&s.cacheNum))
st.NumInserts = s.inserts
st.NumRemoves = s.removes
st.NumMatches = atomic.LoadUint64(&s.matches)
if st.NumMatches > 0 {
st.CacheHitRate = float64(atomic.LoadUint64(&s.cacheHits)) / float64(st.NumMatches)
}
// whip through cache for fanout stats, this can be off if cache is full and doing evictions.
tot, max := 0, 0
clen := 0
s.cache.Range(func(k, v interface{}) bool {
clen++
r := v.(*SublistResult)
l := len(r.psubs) + len(r.qsubs)
tot += l
if l > max {
max = l
}
return true
})
st.MaxFanout = uint32(max)
if tot > 0 {
st.AvgFanout = float64(tot) / float64(clen)
}
return st
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"Stats",
"(",
")",
"*",
"SublistStats",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"Unlock",
"(",
")",
"\n\n",
"st",
":=",
"&",
"SublistStats",
"{",
"}",
"\n",
"st",
".",
"NumSubs",
"=",
"s"... | // Stats will return a stats structure for the current state. | [
"Stats",
"will",
"return",
"a",
"stats",
"structure",
"for",
"the",
"current",
"state",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L693-L725 |
164,296 | nats-io/gnatsd | server/sublist.go | visitLevel | func visitLevel(l *level, depth int) int {
if l == nil || l.numNodes() == 0 {
return depth
}
depth++
maxDepth := depth
for _, n := range l.nodes {
if n == nil {
continue
}
newDepth := visitLevel(n.next, depth)
if newDepth > maxDepth {
maxDepth = newDepth
}
}
if l.pwc != nil {
pwcDepth := visitLevel(l.pwc.next, depth)
if pwcDepth > maxDepth {
maxDepth = pwcDepth
}
}
if l.fwc != nil {
fwcDepth := visitLevel(l.fwc.next, depth)
if fwcDepth > maxDepth {
maxDepth = fwcDepth
}
}
return maxDepth
} | go | func visitLevel(l *level, depth int) int {
if l == nil || l.numNodes() == 0 {
return depth
}
depth++
maxDepth := depth
for _, n := range l.nodes {
if n == nil {
continue
}
newDepth := visitLevel(n.next, depth)
if newDepth > maxDepth {
maxDepth = newDepth
}
}
if l.pwc != nil {
pwcDepth := visitLevel(l.pwc.next, depth)
if pwcDepth > maxDepth {
maxDepth = pwcDepth
}
}
if l.fwc != nil {
fwcDepth := visitLevel(l.fwc.next, depth)
if fwcDepth > maxDepth {
maxDepth = fwcDepth
}
}
return maxDepth
} | [
"func",
"visitLevel",
"(",
"l",
"*",
"level",
",",
"depth",
"int",
")",
"int",
"{",
"if",
"l",
"==",
"nil",
"||",
"l",
".",
"numNodes",
"(",
")",
"==",
"0",
"{",
"return",
"depth",
"\n",
"}",
"\n\n",
"depth",
"++",
"\n",
"maxDepth",
":=",
"depth"... | // visitLevel is used to descend the Sublist tree structure
// recursively. | [
"visitLevel",
"is",
"used",
"to",
"descend",
"the",
"Sublist",
"tree",
"structure",
"recursively",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L735-L765 |
164,297 | nats-io/gnatsd | server/sublist.go | subjectIsLiteral | func subjectIsLiteral(subject string) bool {
for i, c := range subject {
if c == pwc || c == fwc {
if (i == 0 || subject[i-1] == btsep) &&
(i+1 == len(subject) || subject[i+1] == btsep) {
return false
}
}
}
return true
} | go | func subjectIsLiteral(subject string) bool {
for i, c := range subject {
if c == pwc || c == fwc {
if (i == 0 || subject[i-1] == btsep) &&
(i+1 == len(subject) || subject[i+1] == btsep) {
return false
}
}
}
return true
} | [
"func",
"subjectIsLiteral",
"(",
"subject",
"string",
")",
"bool",
"{",
"for",
"i",
",",
"c",
":=",
"range",
"subject",
"{",
"if",
"c",
"==",
"pwc",
"||",
"c",
"==",
"fwc",
"{",
"if",
"(",
"i",
"==",
"0",
"||",
"subject",
"[",
"i",
"-",
"1",
"]... | // Determine if the subject has any wildcards. Fast version, does not check for
// valid subject. Used in caching layer. | [
"Determine",
"if",
"the",
"subject",
"has",
"any",
"wildcards",
".",
"Fast",
"version",
"does",
"not",
"check",
"for",
"valid",
"subject",
".",
"Used",
"in",
"caching",
"layer",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L774-L784 |
164,298 | nats-io/gnatsd | server/sublist.go | IsValidSubject | func IsValidSubject(subject string) bool {
if subject == "" {
return false
}
sfwc := false
tokens := strings.Split(subject, tsep)
for _, t := range tokens {
if len(t) == 0 || sfwc {
return false
}
if len(t) > 1 {
continue
}
switch t[0] {
case fwc:
sfwc = true
}
}
return true
} | go | func IsValidSubject(subject string) bool {
if subject == "" {
return false
}
sfwc := false
tokens := strings.Split(subject, tsep)
for _, t := range tokens {
if len(t) == 0 || sfwc {
return false
}
if len(t) > 1 {
continue
}
switch t[0] {
case fwc:
sfwc = true
}
}
return true
} | [
"func",
"IsValidSubject",
"(",
"subject",
"string",
")",
"bool",
"{",
"if",
"subject",
"==",
"\"",
"\"",
"{",
"return",
"false",
"\n",
"}",
"\n",
"sfwc",
":=",
"false",
"\n",
"tokens",
":=",
"strings",
".",
"Split",
"(",
"subject",
",",
"tsep",
")",
... | // IsValidSubject returns true if a subject is valid, false otherwise | [
"IsValidSubject",
"returns",
"true",
"if",
"a",
"subject",
"is",
"valid",
"false",
"otherwise"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L787-L806 |
164,299 | nats-io/gnatsd | server/sublist.go | localSubs | func (s *Sublist) localSubs(subs *[]*subscription) {
s.RLock()
s.collectLocalSubs(s.root, subs)
s.RUnlock()
} | go | func (s *Sublist) localSubs(subs *[]*subscription) {
s.RLock()
s.collectLocalSubs(s.root, subs)
s.RUnlock()
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"localSubs",
"(",
"subs",
"*",
"[",
"]",
"*",
"subscription",
")",
"{",
"s",
".",
"RLock",
"(",
")",
"\n",
"s",
".",
"collectLocalSubs",
"(",
"s",
".",
"root",
",",
"subs",
")",
"\n",
"s",
".",
"RUnlock",
... | // Return all local client subscriptions. Use the supplied slice. | [
"Return",
"all",
"local",
"client",
"subscriptions",
".",
"Use",
"the",
"supplied",
"slice",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L998-L1002 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.