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,300 | nats-io/gnatsd | server/sublist.go | All | func (s *Sublist) All(subs *[]*subscription) {
s.RLock()
s.collectAllSubs(s.root, subs)
s.RUnlock()
} | go | func (s *Sublist) All(subs *[]*subscription) {
s.RLock()
s.collectAllSubs(s.root, subs)
s.RUnlock()
} | [
"func",
"(",
"s",
"*",
"Sublist",
")",
"All",
"(",
"subs",
"*",
"[",
"]",
"*",
"subscription",
")",
"{",
"s",
".",
"RLock",
"(",
")",
"\n",
"s",
".",
"collectAllSubs",
"(",
"s",
".",
"root",
",",
"subs",
")",
"\n",
"s",
".",
"RUnlock",
"(",
"... | // Used to collect all subscriptions. | [
"Used",
"to",
"collect",
"all",
"subscriptions",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/sublist.go#L1005-L1009 |
164,301 | nats-io/gnatsd | server/jwt.go | validateTrustedOperators | func validateTrustedOperators(o *Options) error {
if len(o.TrustedOperators) == 0 {
return nil
}
if o.AllowNewAccounts {
return fmt.Errorf("operators do not allow dynamic creation of new accounts")
}
if o.AccountResolver == nil {
return fmt.Errorf("operators require an account resolver to be configured")
}
if len(o.Accounts) > 0 {
return fmt.Errorf("operators do not allow Accounts to be configured directly")
}
if len(o.Users) > 0 || len(o.Nkeys) > 0 {
return fmt.Errorf("operators do not allow users to be configured directly")
}
if len(o.TrustedOperators) > 0 && len(o.TrustedKeys) > 0 {
return fmt.Errorf("conflicting options for 'TrustedKeys' and 'TrustedOperators'")
}
// If we have operators, fill in the trusted keys.
// FIXME(dlc) - We had TrustedKeys before TrustedOperators. The jwt.OperatorClaims
// has a DidSign(). Use that longer term. For now we can expand in place.
for _, opc := range o.TrustedOperators {
if o.TrustedKeys == nil {
o.TrustedKeys = make([]string, 0, 4)
}
o.TrustedKeys = append(o.TrustedKeys, opc.Issuer)
o.TrustedKeys = append(o.TrustedKeys, opc.SigningKeys...)
}
for _, key := range o.TrustedKeys {
if !nkeys.IsValidPublicOperatorKey(key) {
return fmt.Errorf("trusted Keys %q are required to be a valid public operator nkey", key)
}
}
return nil
} | go | func validateTrustedOperators(o *Options) error {
if len(o.TrustedOperators) == 0 {
return nil
}
if o.AllowNewAccounts {
return fmt.Errorf("operators do not allow dynamic creation of new accounts")
}
if o.AccountResolver == nil {
return fmt.Errorf("operators require an account resolver to be configured")
}
if len(o.Accounts) > 0 {
return fmt.Errorf("operators do not allow Accounts to be configured directly")
}
if len(o.Users) > 0 || len(o.Nkeys) > 0 {
return fmt.Errorf("operators do not allow users to be configured directly")
}
if len(o.TrustedOperators) > 0 && len(o.TrustedKeys) > 0 {
return fmt.Errorf("conflicting options for 'TrustedKeys' and 'TrustedOperators'")
}
// If we have operators, fill in the trusted keys.
// FIXME(dlc) - We had TrustedKeys before TrustedOperators. The jwt.OperatorClaims
// has a DidSign(). Use that longer term. For now we can expand in place.
for _, opc := range o.TrustedOperators {
if o.TrustedKeys == nil {
o.TrustedKeys = make([]string, 0, 4)
}
o.TrustedKeys = append(o.TrustedKeys, opc.Issuer)
o.TrustedKeys = append(o.TrustedKeys, opc.SigningKeys...)
}
for _, key := range o.TrustedKeys {
if !nkeys.IsValidPublicOperatorKey(key) {
return fmt.Errorf("trusted Keys %q are required to be a valid public operator nkey", key)
}
}
return nil
} | [
"func",
"validateTrustedOperators",
"(",
"o",
"*",
"Options",
")",
"error",
"{",
"if",
"len",
"(",
"o",
".",
"TrustedOperators",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"o",
".",
"AllowNewAccounts",
"{",
"return",
"fmt",
".",
"Erro... | // validateTrustedOperators will check that we do not have conflicts with
// assigned trusted keys and trusted operators. If operators are defined we
// will expand the trusted keys in options. | [
"validateTrustedOperators",
"will",
"check",
"that",
"we",
"do",
"not",
"have",
"conflicts",
"with",
"assigned",
"trusted",
"keys",
"and",
"trusted",
"operators",
".",
"If",
"operators",
"are",
"defined",
"we",
"will",
"expand",
"the",
"trusted",
"keys",
"in",
... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/jwt.go#L64-L99 |
164,302 | nats-io/gnatsd | server/errors.go | Source | func (e *configErr) Source() string {
return fmt.Sprintf("%s:%d:%d", e.token.SourceFile(), e.token.Line(), e.token.Position())
} | go | func (e *configErr) Source() string {
return fmt.Sprintf("%s:%d:%d", e.token.SourceFile(), e.token.Line(), e.token.Position())
} | [
"func",
"(",
"e",
"*",
"configErr",
")",
"Source",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"e",
".",
"token",
".",
"SourceFile",
"(",
")",
",",
"e",
".",
"token",
".",
"Line",
"(",
")",
",",
"e",
".",
"... | // Source reports the location of a configuration error. | [
"Source",
"reports",
"the",
"location",
"of",
"a",
"configuration",
"error",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/errors.go#L121-L123 |
164,303 | nats-io/gnatsd | server/errors.go | Error | func (e *configErr) Error() string {
if e.token != nil {
return fmt.Sprintf("%s: %s", e.Source(), e.reason)
}
return e.reason
} | go | func (e *configErr) Error() string {
if e.token != nil {
return fmt.Sprintf("%s: %s", e.Source(), e.reason)
}
return e.reason
} | [
"func",
"(",
"e",
"*",
"configErr",
")",
"Error",
"(",
")",
"string",
"{",
"if",
"e",
".",
"token",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"e",
".",
"Source",
"(",
")",
",",
"e",
".",
"reason",
")",
"\n",
"}"... | // Error reports the location and reason from a configuration error. | [
"Error",
"reports",
"the",
"location",
"and",
"reason",
"from",
"a",
"configuration",
"error",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/errors.go#L126-L131 |
164,304 | nats-io/gnatsd | server/errors.go | Error | func (e *unknownConfigFieldErr) Error() string {
return fmt.Sprintf("%s: unknown field %q", e.Source(), e.field)
} | go | func (e *unknownConfigFieldErr) Error() string {
return fmt.Sprintf("%s: unknown field %q", e.Source(), e.field)
} | [
"func",
"(",
"e",
"*",
"unknownConfigFieldErr",
")",
"Error",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"e",
".",
"Source",
"(",
")",
",",
"e",
".",
"field",
")",
"\n",
"}"
] | // Error reports that an unknown field was in the configuration. | [
"Error",
"reports",
"that",
"an",
"unknown",
"field",
"was",
"in",
"the",
"configuration",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/errors.go#L140-L142 |
164,305 | nats-io/gnatsd | server/errors.go | Error | func (e *configWarningErr) Error() string {
return fmt.Sprintf("%s: invalid use of field %q: %s", e.Source(), e.field, e.reason)
} | go | func (e *configWarningErr) Error() string {
return fmt.Sprintf("%s: invalid use of field %q: %s", e.Source(), e.field, e.reason)
} | [
"func",
"(",
"e",
"*",
"configWarningErr",
")",
"Error",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"e",
".",
"Source",
"(",
")",
",",
"e",
".",
"field",
",",
"e",
".",
"reason",
")",
"\n",
"}"
] | // Error reports a configuration warning. | [
"Error",
"reports",
"a",
"configuration",
"warning",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/errors.go#L151-L153 |
164,306 | nats-io/gnatsd | server/errors.go | Error | func (e *processConfigErr) Error() string {
var msg string
for _, err := range e.Warnings() {
msg += err.Error() + "\n"
}
for _, err := range e.Errors() {
msg += err.Error() + "\n"
}
return msg
} | go | func (e *processConfigErr) Error() string {
var msg string
for _, err := range e.Warnings() {
msg += err.Error() + "\n"
}
for _, err := range e.Errors() {
msg += err.Error() + "\n"
}
return msg
} | [
"func",
"(",
"e",
"*",
"processConfigErr",
")",
"Error",
"(",
")",
"string",
"{",
"var",
"msg",
"string",
"\n",
"for",
"_",
",",
"err",
":=",
"range",
"e",
".",
"Warnings",
"(",
")",
"{",
"msg",
"+=",
"err",
".",
"Error",
"(",
")",
"+",
"\"",
"... | // Error returns the collection of errors separated by new lines,
// warnings appear first then hard errors. | [
"Error",
"returns",
"the",
"collection",
"of",
"errors",
"separated",
"by",
"new",
"lines",
"warnings",
"appear",
"first",
"then",
"hard",
"errors",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/errors.go#L163-L172 |
164,307 | nats-io/gnatsd | server/pse/pse_linux.go | periodic | func periodic() {
contents, err := ioutil.ReadFile(procStatFile)
if err != nil {
return
}
fields := bytes.Fields(contents)
// PCPU
pstart := parseInt64(fields[startPos])
utime := parseInt64(fields[utimePos])
stime := parseInt64(fields[stimePos])
total := utime + stime
var sysinfo syscall.Sysinfo_t
if err := syscall.Sysinfo(&sysinfo); err != nil {
return
}
seconds := int64(sysinfo.Uptime) - (pstart / ticks)
// Save off temps
lt := lastTotal
ls := lastSeconds
// Update last sample
lastTotal = total
lastSeconds = seconds
// Adjust to current time window
total -= lt
seconds -= ls
if seconds > 0 {
atomic.StoreInt64(&ipcpu, (total*1000/ticks)/seconds)
}
time.AfterFunc(1*time.Second, periodic)
} | go | func periodic() {
contents, err := ioutil.ReadFile(procStatFile)
if err != nil {
return
}
fields := bytes.Fields(contents)
// PCPU
pstart := parseInt64(fields[startPos])
utime := parseInt64(fields[utimePos])
stime := parseInt64(fields[stimePos])
total := utime + stime
var sysinfo syscall.Sysinfo_t
if err := syscall.Sysinfo(&sysinfo); err != nil {
return
}
seconds := int64(sysinfo.Uptime) - (pstart / ticks)
// Save off temps
lt := lastTotal
ls := lastSeconds
// Update last sample
lastTotal = total
lastSeconds = seconds
// Adjust to current time window
total -= lt
seconds -= ls
if seconds > 0 {
atomic.StoreInt64(&ipcpu, (total*1000/ticks)/seconds)
}
time.AfterFunc(1*time.Second, periodic)
} | [
"func",
"periodic",
"(",
")",
"{",
"contents",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"procStatFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"fields",
":=",
"bytes",
".",
"Fields",
"(",
"contents",
")",
"\n\n"... | // Sampling function to keep pcpu relevant. | [
"Sampling",
"function",
"to",
"keep",
"pcpu",
"relevant",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/pse/pse_linux.go#L50-L87 |
164,308 | nats-io/gnatsd | server/events.go | internalSendLoop | func (s *Server) internalSendLoop(wg *sync.WaitGroup) {
defer wg.Done()
s.mu.Lock()
if s.sys == nil || s.sys.sendq == nil {
s.mu.Unlock()
return
}
c := s.sys.client
sendq := s.sys.sendq
id := s.info.ID
host := s.info.Host
seqp := &s.sys.seq
var cluster string
if s.gateway.enabled {
cluster = s.getGatewayName()
}
s.mu.Unlock()
for s.eventsRunning() {
// Setup information for next message
seq := atomic.AddUint64(seqp, 1)
select {
case pm := <-sendq:
if pm.si != nil {
pm.si.Host = host
pm.si.Cluster = cluster
pm.si.ID = id
pm.si.Seq = seq
pm.si.Version = VERSION
pm.si.Time = time.Now()
}
var b []byte
if pm.msg != nil {
b, _ = json.MarshalIndent(pm.msg, _EMPTY_, " ")
}
// Prep internal structures needed to send message.
c.pa.subject = []byte(pm.sub)
c.pa.size = len(b)
c.pa.szb = []byte(strconv.FormatInt(int64(len(b)), 10))
c.pa.reply = []byte(pm.rply)
// Add in NL
b = append(b, _CRLF_...)
c.processInboundClientMsg(b)
c.flushClients(0) // Never spend time in place.
// See if we are doing graceful shutdown.
if pm.last {
return
}
case <-s.quitCh:
return
}
}
} | go | func (s *Server) internalSendLoop(wg *sync.WaitGroup) {
defer wg.Done()
s.mu.Lock()
if s.sys == nil || s.sys.sendq == nil {
s.mu.Unlock()
return
}
c := s.sys.client
sendq := s.sys.sendq
id := s.info.ID
host := s.info.Host
seqp := &s.sys.seq
var cluster string
if s.gateway.enabled {
cluster = s.getGatewayName()
}
s.mu.Unlock()
for s.eventsRunning() {
// Setup information for next message
seq := atomic.AddUint64(seqp, 1)
select {
case pm := <-sendq:
if pm.si != nil {
pm.si.Host = host
pm.si.Cluster = cluster
pm.si.ID = id
pm.si.Seq = seq
pm.si.Version = VERSION
pm.si.Time = time.Now()
}
var b []byte
if pm.msg != nil {
b, _ = json.MarshalIndent(pm.msg, _EMPTY_, " ")
}
// Prep internal structures needed to send message.
c.pa.subject = []byte(pm.sub)
c.pa.size = len(b)
c.pa.szb = []byte(strconv.FormatInt(int64(len(b)), 10))
c.pa.reply = []byte(pm.rply)
// Add in NL
b = append(b, _CRLF_...)
c.processInboundClientMsg(b)
c.flushClients(0) // Never spend time in place.
// See if we are doing graceful shutdown.
if pm.last {
return
}
case <-s.quitCh:
return
}
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"internalSendLoop",
"(",
"wg",
"*",
"sync",
".",
"WaitGroup",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"sys",
"==",
"nil",
"||",
... | // internalSendLoop will be responsible for serializing all messages that
// a server wants to send. | [
"internalSendLoop",
"will",
"be",
"responsible",
"for",
"serializing",
"all",
"messages",
"that",
"a",
"server",
"wants",
"to",
"send",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L184-L237 |
164,309 | nats-io/gnatsd | server/events.go | sendShutdownEvent | func (s *Server) sendShutdownEvent() {
s.mu.Lock()
if s.sys == nil || s.sys.sendq == nil {
s.mu.Unlock()
return
}
subj := fmt.Sprintf(shutdownEventSubj, s.info.ID)
sendq := s.sys.sendq
// Stop any more messages from queueing up.
s.sys.sendq = nil
// Unhook all msgHandlers. Normal client cleanup will deal with subs, etc.
s.sys.subs = nil
s.mu.Unlock()
// Send to the internal queue and mark as last.
sendq <- &pubMsg{subj, _EMPTY_, nil, nil, true}
} | go | func (s *Server) sendShutdownEvent() {
s.mu.Lock()
if s.sys == nil || s.sys.sendq == nil {
s.mu.Unlock()
return
}
subj := fmt.Sprintf(shutdownEventSubj, s.info.ID)
sendq := s.sys.sendq
// Stop any more messages from queueing up.
s.sys.sendq = nil
// Unhook all msgHandlers. Normal client cleanup will deal with subs, etc.
s.sys.subs = nil
s.mu.Unlock()
// Send to the internal queue and mark as last.
sendq <- &pubMsg{subj, _EMPTY_, nil, nil, true}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendShutdownEvent",
"(",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"sys",
"==",
"nil",
"||",
"s",
".",
"sys",
".",
"sendq",
"==",
"nil",
"{",
"s",
".",
"mu",
".",
"Unlock",
... | // Will send a shutdown message. | [
"Will",
"send",
"a",
"shutdown",
"message",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L240-L255 |
164,310 | nats-io/gnatsd | server/events.go | sendInternalMsg | func (s *Server) sendInternalMsg(sub, rply string, si *ServerInfo, msg interface{}) {
if s.sys == nil || s.sys.sendq == nil {
return
}
sendq := s.sys.sendq
// Don't hold lock while placing on the channel.
s.mu.Unlock()
sendq <- &pubMsg{sub, rply, si, msg, false}
s.mu.Lock()
} | go | func (s *Server) sendInternalMsg(sub, rply string, si *ServerInfo, msg interface{}) {
if s.sys == nil || s.sys.sendq == nil {
return
}
sendq := s.sys.sendq
// Don't hold lock while placing on the channel.
s.mu.Unlock()
sendq <- &pubMsg{sub, rply, si, msg, false}
s.mu.Lock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendInternalMsg",
"(",
"sub",
",",
"rply",
"string",
",",
"si",
"*",
"ServerInfo",
",",
"msg",
"interface",
"{",
"}",
")",
"{",
"if",
"s",
".",
"sys",
"==",
"nil",
"||",
"s",
".",
"sys",
".",
"sendq",
"==",
... | // This will queue up a message to be sent.
// Assumes lock is held on entry. | [
"This",
"will",
"queue",
"up",
"a",
"message",
"to",
"be",
"sent",
".",
"Assumes",
"lock",
"is",
"held",
"on",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L259-L268 |
164,311 | nats-io/gnatsd | server/events.go | eventsRunning | func (s *Server) eventsRunning() bool {
s.mu.Lock()
er := s.running && s.eventsEnabled()
s.mu.Unlock()
return er
} | go | func (s *Server) eventsRunning() bool {
s.mu.Lock()
er := s.running && s.eventsEnabled()
s.mu.Unlock()
return er
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"eventsRunning",
"(",
")",
"bool",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"er",
":=",
"s",
".",
"running",
"&&",
"s",
".",
"eventsEnabled",
"(",
")",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
"... | // Locked version of checking if events system running. Also checks server. | [
"Locked",
"version",
"of",
"checking",
"if",
"events",
"system",
"running",
".",
"Also",
"checks",
"server",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L271-L276 |
164,312 | nats-io/gnatsd | server/events.go | EventsEnabled | func (s *Server) EventsEnabled() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.eventsEnabled()
} | go | func (s *Server) EventsEnabled() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.eventsEnabled()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"EventsEnabled",
"(",
")",
"bool",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"s",
".",
"eventsEnabled",
"(",
")",
"\n",
"}"
] | // EventsEnabled will report if the server has internal events enabled via
// a defined system account. | [
"EventsEnabled",
"will",
"report",
"if",
"the",
"server",
"has",
"internal",
"events",
"enabled",
"via",
"a",
"defined",
"system",
"account",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L280-L284 |
164,313 | nats-io/gnatsd | server/events.go | eventsEnabled | func (s *Server) eventsEnabled() bool {
return s.sys != nil && s.sys.client != nil && s.sys.account != nil
} | go | func (s *Server) eventsEnabled() bool {
return s.sys != nil && s.sys.client != nil && s.sys.account != nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"eventsEnabled",
"(",
")",
"bool",
"{",
"return",
"s",
".",
"sys",
"!=",
"nil",
"&&",
"s",
".",
"sys",
".",
"client",
"!=",
"nil",
"&&",
"s",
".",
"sys",
".",
"account",
"!=",
"nil",
"\n",
"}"
] | // eventsEnabled will report if events are enabled.
// Lock should be held. | [
"eventsEnabled",
"will",
"report",
"if",
"events",
"are",
"enabled",
".",
"Lock",
"should",
"be",
"held",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L288-L290 |
164,314 | nats-io/gnatsd | server/events.go | routeStat | func routeStat(r *client) *RouteStat {
if r == nil {
return nil
}
r.mu.Lock()
rs := &RouteStat{
ID: r.cid,
Sent: DataStats{
Msgs: atomic.LoadInt64(&r.outMsgs),
Bytes: atomic.LoadInt64(&r.outBytes),
},
Received: DataStats{
Msgs: atomic.LoadInt64(&r.inMsgs),
Bytes: atomic.LoadInt64(&r.inBytes),
},
Pending: int(r.out.pb),
}
r.mu.Unlock()
return rs
} | go | func routeStat(r *client) *RouteStat {
if r == nil {
return nil
}
r.mu.Lock()
rs := &RouteStat{
ID: r.cid,
Sent: DataStats{
Msgs: atomic.LoadInt64(&r.outMsgs),
Bytes: atomic.LoadInt64(&r.outBytes),
},
Received: DataStats{
Msgs: atomic.LoadInt64(&r.inMsgs),
Bytes: atomic.LoadInt64(&r.inBytes),
},
Pending: int(r.out.pb),
}
r.mu.Unlock()
return rs
} | [
"func",
"routeStat",
"(",
"r",
"*",
"client",
")",
"*",
"RouteStat",
"{",
"if",
"r",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"r",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"rs",
":=",
"&",
"RouteStat",
"{",
"ID",
":",
"r",
".",
"cid... | // Generate a route stat for our statz update. | [
"Generate",
"a",
"route",
"stat",
"for",
"our",
"statz",
"update",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L320-L339 |
164,315 | nats-io/gnatsd | server/events.go | sendStatsz | func (s *Server) sendStatsz(subj string) {
m := ServerStatsMsg{}
updateServerUsage(&m.Stats)
m.Stats.Start = s.start
m.Stats.Connections = len(s.clients)
m.Stats.TotalConnections = s.totalClients
m.Stats.ActiveAccounts = int(atomic.LoadInt32(&s.activeAccounts))
m.Stats.Received.Msgs = atomic.LoadInt64(&s.inMsgs)
m.Stats.Received.Bytes = atomic.LoadInt64(&s.inBytes)
m.Stats.Sent.Msgs = atomic.LoadInt64(&s.outMsgs)
m.Stats.Sent.Bytes = atomic.LoadInt64(&s.outBytes)
m.Stats.SlowConsumers = atomic.LoadInt64(&s.slowConsumers)
m.Stats.NumSubs = s.numSubscriptions()
for _, r := range s.routes {
m.Stats.Routes = append(m.Stats.Routes, routeStat(r))
}
if s.gateway.enabled {
gw := s.gateway
gw.RLock()
for name, c := range gw.out {
gs := &GatewayStat{Name: name}
c.mu.Lock()
gs.ID = c.cid
gs.Sent = DataStats{
Msgs: atomic.LoadInt64(&c.outMsgs),
Bytes: atomic.LoadInt64(&c.outBytes),
}
c.mu.Unlock()
// Gather matching inbound connections
gs.Received = DataStats{}
for _, c := range gw.in {
c.mu.Lock()
if c.gw.name == name {
gs.Received.Msgs += atomic.LoadInt64(&c.inMsgs)
gs.Received.Bytes += atomic.LoadInt64(&c.inBytes)
gs.NumInbound++
}
c.mu.Unlock()
}
m.Stats.Gateways = append(m.Stats.Gateways, gs)
}
gw.RUnlock()
}
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
} | go | func (s *Server) sendStatsz(subj string) {
m := ServerStatsMsg{}
updateServerUsage(&m.Stats)
m.Stats.Start = s.start
m.Stats.Connections = len(s.clients)
m.Stats.TotalConnections = s.totalClients
m.Stats.ActiveAccounts = int(atomic.LoadInt32(&s.activeAccounts))
m.Stats.Received.Msgs = atomic.LoadInt64(&s.inMsgs)
m.Stats.Received.Bytes = atomic.LoadInt64(&s.inBytes)
m.Stats.Sent.Msgs = atomic.LoadInt64(&s.outMsgs)
m.Stats.Sent.Bytes = atomic.LoadInt64(&s.outBytes)
m.Stats.SlowConsumers = atomic.LoadInt64(&s.slowConsumers)
m.Stats.NumSubs = s.numSubscriptions()
for _, r := range s.routes {
m.Stats.Routes = append(m.Stats.Routes, routeStat(r))
}
if s.gateway.enabled {
gw := s.gateway
gw.RLock()
for name, c := range gw.out {
gs := &GatewayStat{Name: name}
c.mu.Lock()
gs.ID = c.cid
gs.Sent = DataStats{
Msgs: atomic.LoadInt64(&c.outMsgs),
Bytes: atomic.LoadInt64(&c.outBytes),
}
c.mu.Unlock()
// Gather matching inbound connections
gs.Received = DataStats{}
for _, c := range gw.in {
c.mu.Lock()
if c.gw.name == name {
gs.Received.Msgs += atomic.LoadInt64(&c.inMsgs)
gs.Received.Bytes += atomic.LoadInt64(&c.inBytes)
gs.NumInbound++
}
c.mu.Unlock()
}
m.Stats.Gateways = append(m.Stats.Gateways, gs)
}
gw.RUnlock()
}
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendStatsz",
"(",
"subj",
"string",
")",
"{",
"m",
":=",
"ServerStatsMsg",
"{",
"}",
"\n",
"updateServerUsage",
"(",
"&",
"m",
".",
"Stats",
")",
"\n",
"m",
".",
"Stats",
".",
"Start",
"=",
"s",
".",
"start",
... | // Actual send method for statz updates.
// Lock should be held. | [
"Actual",
"send",
"method",
"for",
"statz",
"updates",
".",
"Lock",
"should",
"be",
"held",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L343-L388 |
164,316 | nats-io/gnatsd | server/events.go | initEventTracking | func (s *Server) initEventTracking() {
if !s.eventsEnabled() {
return
}
subject := fmt.Sprintf(accConnsEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.remoteConnsUpdate); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// This will be for responses for account info that we send out.
subject = fmt.Sprintf(connsRespSubj, s.info.ID)
if _, err := s.sysSubscribe(subject, s.remoteConnsUpdate); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for broad requests to respond with account info.
subject = fmt.Sprintf(accConnsReqSubj, "*")
if _, err := s.sysSubscribe(subject, s.connsRequest); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for all server shutdowns.
subject = fmt.Sprintf(shutdownEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.remoteServerShutdown); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for account claims updates.
subject = fmt.Sprintf(accUpdateEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.accountClaimUpdate); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for requests for our statsz.
subject = fmt.Sprintf(serverStatsReqSubj, s.info.ID)
if _, err := s.sysSubscribe(subject, s.statszReq); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for ping messages that will be sent to all servers for statsz.
if _, err := s.sysSubscribe(serverStatsPingReqSubj, s.statszReq); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for updates when leaf nodes connect for a given account. This will
// force any gateway connections to move to `modeInterestOnly`
subject = fmt.Sprintf(leafNodeConnectEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.leafNodeConnected); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
} | go | func (s *Server) initEventTracking() {
if !s.eventsEnabled() {
return
}
subject := fmt.Sprintf(accConnsEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.remoteConnsUpdate); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// This will be for responses for account info that we send out.
subject = fmt.Sprintf(connsRespSubj, s.info.ID)
if _, err := s.sysSubscribe(subject, s.remoteConnsUpdate); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for broad requests to respond with account info.
subject = fmt.Sprintf(accConnsReqSubj, "*")
if _, err := s.sysSubscribe(subject, s.connsRequest); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for all server shutdowns.
subject = fmt.Sprintf(shutdownEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.remoteServerShutdown); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for account claims updates.
subject = fmt.Sprintf(accUpdateEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.accountClaimUpdate); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for requests for our statsz.
subject = fmt.Sprintf(serverStatsReqSubj, s.info.ID)
if _, err := s.sysSubscribe(subject, s.statszReq); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for ping messages that will be sent to all servers for statsz.
if _, err := s.sysSubscribe(serverStatsPingReqSubj, s.statszReq); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
// Listen for updates when leaf nodes connect for a given account. This will
// force any gateway connections to move to `modeInterestOnly`
subject = fmt.Sprintf(leafNodeConnectEventSubj, "*")
if _, err := s.sysSubscribe(subject, s.leafNodeConnected); err != nil {
s.Errorf("Error setting up internal tracking: %v", err)
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"initEventTracking",
"(",
")",
"{",
"if",
"!",
"s",
".",
"eventsEnabled",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"subject",
":=",
"fmt",
".",
"Sprintf",
"(",
"accConnsEventSubj",
",",
"\"",
"\"",
")",
"\n",
... | // This will setup our system wide tracking subs.
// For now we will setup one wildcard subscription to
// monitor all accounts for changes in number of connections.
// We can make this on a per account tracking basis if needed.
// Tradeoff is subscription and interest graph events vs connect and
// disconnect events, etc. | [
"This",
"will",
"setup",
"our",
"system",
"wide",
"tracking",
"subs",
".",
"For",
"now",
"we",
"will",
"setup",
"one",
"wildcard",
"subscription",
"to",
"monitor",
"all",
"accounts",
"for",
"changes",
"in",
"number",
"of",
"connections",
".",
"We",
"can",
... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L416-L459 |
164,317 | nats-io/gnatsd | server/events.go | accountClaimUpdate | func (s *Server) accountClaimUpdate(sub *subscription, subject, reply string, msg []byte) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() {
return
}
toks := strings.Split(subject, tsep)
if len(toks) < accUpdateTokens {
s.Debugf("Received account claims update on bad subject %q", subject)
return
}
if v, ok := s.accounts.Load(toks[accUpdateAccIndex]); ok {
s.updateAccountWithClaimJWT(v.(*Account), string(msg))
}
} | go | func (s *Server) accountClaimUpdate(sub *subscription, subject, reply string, msg []byte) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() {
return
}
toks := strings.Split(subject, tsep)
if len(toks) < accUpdateTokens {
s.Debugf("Received account claims update on bad subject %q", subject)
return
}
if v, ok := s.accounts.Load(toks[accUpdateAccIndex]); ok {
s.updateAccountWithClaimJWT(v.(*Account), string(msg))
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"accountClaimUpdate",
"(",
"sub",
"*",
"subscription",
",",
"subject",
",",
"reply",
"string",
",",
"msg",
"[",
"]",
"byte",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
"."... | // accountClaimUpdate will receive claim updates for accounts. | [
"accountClaimUpdate",
"will",
"receive",
"claim",
"updates",
"for",
"accounts",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L462-L476 |
164,318 | nats-io/gnatsd | server/events.go | processRemoteServerShutdown | func (s *Server) processRemoteServerShutdown(sid string) {
s.accounts.Range(func(k, v interface{}) bool {
a := v.(*Account)
a.mu.Lock()
prev := a.strack[sid]
delete(a.strack, sid)
a.nrclients -= prev.conns
a.nrleafs -= prev.leafs
a.mu.Unlock()
return true
})
} | go | func (s *Server) processRemoteServerShutdown(sid string) {
s.accounts.Range(func(k, v interface{}) bool {
a := v.(*Account)
a.mu.Lock()
prev := a.strack[sid]
delete(a.strack, sid)
a.nrclients -= prev.conns
a.nrleafs -= prev.leafs
a.mu.Unlock()
return true
})
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"processRemoteServerShutdown",
"(",
"sid",
"string",
")",
"{",
"s",
".",
"accounts",
".",
"Range",
"(",
"func",
"(",
"k",
",",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"a",
":=",
"v",
".",
"(",
"*",
"Acc... | // processRemoteServerShutdown will update any affected accounts.
// Will update the remote count for clients.
// Lock assume held. | [
"processRemoteServerShutdown",
"will",
"update",
"any",
"affected",
"accounts",
".",
"Will",
"update",
"the",
"remote",
"count",
"for",
"clients",
".",
"Lock",
"assume",
"held",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L481-L492 |
164,319 | nats-io/gnatsd | server/events.go | remoteServerShutdown | func (s *Server) remoteServerShutdown(sub *subscription, subject, reply string, msg []byte) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() {
return
}
toks := strings.Split(subject, tsep)
if len(toks) < shutdownEventTokens {
s.Debugf("Received remote server shutdown on bad subject %q", subject)
return
}
sid := toks[serverSubjectIndex]
su := s.sys.servers[sid]
if su != nil {
s.processRemoteServerShutdown(sid)
}
} | go | func (s *Server) remoteServerShutdown(sub *subscription, subject, reply string, msg []byte) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() {
return
}
toks := strings.Split(subject, tsep)
if len(toks) < shutdownEventTokens {
s.Debugf("Received remote server shutdown on bad subject %q", subject)
return
}
sid := toks[serverSubjectIndex]
su := s.sys.servers[sid]
if su != nil {
s.processRemoteServerShutdown(sid)
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"remoteServerShutdown",
"(",
"sub",
"*",
"subscription",
",",
"subject",
",",
"reply",
"string",
",",
"msg",
"[",
"]",
"byte",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
"... | // remoteServerShutdownEvent is called when we get an event from another server shutting down. | [
"remoteServerShutdownEvent",
"is",
"called",
"when",
"we",
"get",
"an",
"event",
"from",
"another",
"server",
"shutting",
"down",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L495-L511 |
164,320 | nats-io/gnatsd | server/events.go | updateRemoteServer | func (s *Server) updateRemoteServer(ms *ServerInfo) {
su := s.sys.servers[ms.ID]
if su == nil {
s.sys.servers[ms.ID] = &serverUpdate{ms.Seq, time.Now()}
} else {
// Should alwqys be going up.
if ms.Seq <= su.seq {
s.Errorf("Received out of order remote server update from: %q", ms.ID)
return
}
su.seq = ms.Seq
su.ltime = time.Now()
}
} | go | func (s *Server) updateRemoteServer(ms *ServerInfo) {
su := s.sys.servers[ms.ID]
if su == nil {
s.sys.servers[ms.ID] = &serverUpdate{ms.Seq, time.Now()}
} else {
// Should alwqys be going up.
if ms.Seq <= su.seq {
s.Errorf("Received out of order remote server update from: %q", ms.ID)
return
}
su.seq = ms.Seq
su.ltime = time.Now()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"updateRemoteServer",
"(",
"ms",
"*",
"ServerInfo",
")",
"{",
"su",
":=",
"s",
".",
"sys",
".",
"servers",
"[",
"ms",
".",
"ID",
"]",
"\n",
"if",
"su",
"==",
"nil",
"{",
"s",
".",
"sys",
".",
"servers",
"["... | // updateRemoteServer is called when we have an update from a remote server.
// This allows us to track remote servers, respond to shutdown messages properly,
// make sure that messages are ordered, and allow us to prune dead servers.
// Lock should be held upon entry. | [
"updateRemoteServer",
"is",
"called",
"when",
"we",
"have",
"an",
"update",
"from",
"a",
"remote",
"server",
".",
"This",
"allows",
"us",
"to",
"track",
"remote",
"servers",
"respond",
"to",
"shutdown",
"messages",
"properly",
"make",
"sure",
"that",
"messages... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L517-L530 |
164,321 | nats-io/gnatsd | server/events.go | shutdownEventing | func (s *Server) shutdownEventing() {
if !s.eventsRunning() {
return
}
s.mu.Lock()
clearTimer(&s.sys.sweeper)
clearTimer(&s.sys.stmr)
s.mu.Unlock()
// We will queue up a shutdown event and wait for the
// internal send loop to exit.
s.sendShutdownEvent()
s.sys.wg.Wait()
s.mu.Lock()
defer s.mu.Unlock()
// Whip through all accounts.
s.accounts.Range(func(k, v interface{}) bool {
a := v.(*Account)
a.mu.Lock()
a.nrclients = 0
// Now clear state
clearTimer(&a.etmr)
clearTimer(&a.ctmr)
a.clients = nil
a.strack = nil
a.mu.Unlock()
return true
})
// Turn everything off here.
s.sys = nil
} | go | func (s *Server) shutdownEventing() {
if !s.eventsRunning() {
return
}
s.mu.Lock()
clearTimer(&s.sys.sweeper)
clearTimer(&s.sys.stmr)
s.mu.Unlock()
// We will queue up a shutdown event and wait for the
// internal send loop to exit.
s.sendShutdownEvent()
s.sys.wg.Wait()
s.mu.Lock()
defer s.mu.Unlock()
// Whip through all accounts.
s.accounts.Range(func(k, v interface{}) bool {
a := v.(*Account)
a.mu.Lock()
a.nrclients = 0
// Now clear state
clearTimer(&a.etmr)
clearTimer(&a.ctmr)
a.clients = nil
a.strack = nil
a.mu.Unlock()
return true
})
// Turn everything off here.
s.sys = nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"shutdownEventing",
"(",
")",
"{",
"if",
"!",
"s",
".",
"eventsRunning",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"clearTimer",
"(",
"&",
"s",
".",
"sys",
"."... | // shutdownEventing will clean up all eventing state. | [
"shutdownEventing",
"will",
"clean",
"up",
"all",
"eventing",
"state",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L533-L566 |
164,322 | nats-io/gnatsd | server/events.go | connsRequest | func (s *Server) connsRequest(sub *subscription, subject, reply string, msg []byte) {
if !s.eventsRunning() {
return
}
m := accNumConnsReq{}
if err := json.Unmarshal(msg, &m); err != nil {
s.sys.client.Errorf("Error unmarshalling account connections request message: %v", err)
return
}
acc, _ := s.lookupAccount(m.Account)
if acc == nil {
return
}
if nlc := acc.NumLocalConnections(); nlc > 0 {
s.mu.Lock()
s.sendAccConnsUpdate(acc, reply)
s.mu.Unlock()
}
} | go | func (s *Server) connsRequest(sub *subscription, subject, reply string, msg []byte) {
if !s.eventsRunning() {
return
}
m := accNumConnsReq{}
if err := json.Unmarshal(msg, &m); err != nil {
s.sys.client.Errorf("Error unmarshalling account connections request message: %v", err)
return
}
acc, _ := s.lookupAccount(m.Account)
if acc == nil {
return
}
if nlc := acc.NumLocalConnections(); nlc > 0 {
s.mu.Lock()
s.sendAccConnsUpdate(acc, reply)
s.mu.Unlock()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"connsRequest",
"(",
"sub",
"*",
"subscription",
",",
"subject",
",",
"reply",
"string",
",",
"msg",
"[",
"]",
"byte",
")",
"{",
"if",
"!",
"s",
".",
"eventsRunning",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
... | // Request for our local connection count. | [
"Request",
"for",
"our",
"local",
"connection",
"count",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L569-L587 |
164,323 | nats-io/gnatsd | server/events.go | leafNodeConnected | func (s *Server) leafNodeConnected(sub *subscription, subject, reply string, msg []byte) {
m := accNumConnsReq{}
if err := json.Unmarshal(msg, &m); err != nil {
s.sys.client.Errorf("Error unmarshalling account connections request message: %v", err)
return
}
s.mu.Lock()
na := m.Account == "" || !s.eventsEnabled() || !s.gateway.enabled
s.mu.Unlock()
if na {
return
}
if acc, _ := s.lookupAccount(m.Account); acc != nil {
s.switchAccountToInterestMode(acc.Name)
}
} | go | func (s *Server) leafNodeConnected(sub *subscription, subject, reply string, msg []byte) {
m := accNumConnsReq{}
if err := json.Unmarshal(msg, &m); err != nil {
s.sys.client.Errorf("Error unmarshalling account connections request message: %v", err)
return
}
s.mu.Lock()
na := m.Account == "" || !s.eventsEnabled() || !s.gateway.enabled
s.mu.Unlock()
if na {
return
}
if acc, _ := s.lookupAccount(m.Account); acc != nil {
s.switchAccountToInterestMode(acc.Name)
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"leafNodeConnected",
"(",
"sub",
"*",
"subscription",
",",
"subject",
",",
"reply",
"string",
",",
"msg",
"[",
"]",
"byte",
")",
"{",
"m",
":=",
"accNumConnsReq",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
... | // leafNodeConnected is an event we will receive when a leaf node for a given account
// connects. | [
"leafNodeConnected",
"is",
"an",
"event",
"we",
"will",
"receive",
"when",
"a",
"leaf",
"node",
"for",
"a",
"given",
"account",
"connects",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L591-L609 |
164,324 | nats-io/gnatsd | server/events.go | statszReq | func (s *Server) statszReq(sub *subscription, subject, reply string, msg []byte) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() || reply == _EMPTY_ {
return
}
s.sendStatsz(reply)
} | go | func (s *Server) statszReq(sub *subscription, subject, reply string, msg []byte) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() || reply == _EMPTY_ {
return
}
s.sendStatsz(reply)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"statszReq",
"(",
"sub",
"*",
"subscription",
",",
"subject",
",",
"reply",
"string",
",",
"msg",
"[",
"]",
"byte",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlo... | // statszReq is a request for us to respond with current statz. | [
"statszReq",
"is",
"a",
"request",
"for",
"us",
"to",
"respond",
"with",
"current",
"statz",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L612-L619 |
164,325 | nats-io/gnatsd | server/events.go | remoteConnsUpdate | func (s *Server) remoteConnsUpdate(sub *subscription, subject, reply string, msg []byte) {
if !s.eventsRunning() {
return
}
m := AccountNumConns{}
if err := json.Unmarshal(msg, &m); err != nil {
s.sys.client.Errorf("Error unmarshalling account connection event message: %v", err)
return
}
// See if we have the account registered, if not drop it.
acc, _ := s.lookupAccount(m.Account)
s.mu.Lock()
defer s.mu.Unlock()
// check again here if we have been shutdown.
if !s.running || !s.eventsEnabled() {
return
}
// Double check that this is not us, should never happen, so error if it does.
if m.Server.ID == s.info.ID {
s.sys.client.Errorf("Processing our own account connection event message: ignored")
return
}
if acc == nil {
s.sys.client.Debugf("Received account connection event for unknown account: %s", m.Account)
return
}
// If we are here we have interest in tracking this account. Update our accounting.
acc.mu.Lock()
if acc.strack == nil {
acc.strack = make(map[string]sconns)
}
// This does not depend on receiving all updates since each one is idempotent.
prev := acc.strack[m.Server.ID]
acc.strack[m.Server.ID] = sconns{conns: int32(m.Conns), leafs: int32(m.LeafNodes)}
acc.nrclients += int32(m.Conns) - prev.conns
acc.nrleafs += int32(m.LeafNodes) - prev.leafs
acc.mu.Unlock()
s.updateRemoteServer(&m.Server)
} | go | func (s *Server) remoteConnsUpdate(sub *subscription, subject, reply string, msg []byte) {
if !s.eventsRunning() {
return
}
m := AccountNumConns{}
if err := json.Unmarshal(msg, &m); err != nil {
s.sys.client.Errorf("Error unmarshalling account connection event message: %v", err)
return
}
// See if we have the account registered, if not drop it.
acc, _ := s.lookupAccount(m.Account)
s.mu.Lock()
defer s.mu.Unlock()
// check again here if we have been shutdown.
if !s.running || !s.eventsEnabled() {
return
}
// Double check that this is not us, should never happen, so error if it does.
if m.Server.ID == s.info.ID {
s.sys.client.Errorf("Processing our own account connection event message: ignored")
return
}
if acc == nil {
s.sys.client.Debugf("Received account connection event for unknown account: %s", m.Account)
return
}
// If we are here we have interest in tracking this account. Update our accounting.
acc.mu.Lock()
if acc.strack == nil {
acc.strack = make(map[string]sconns)
}
// This does not depend on receiving all updates since each one is idempotent.
prev := acc.strack[m.Server.ID]
acc.strack[m.Server.ID] = sconns{conns: int32(m.Conns), leafs: int32(m.LeafNodes)}
acc.nrclients += int32(m.Conns) - prev.conns
acc.nrleafs += int32(m.LeafNodes) - prev.leafs
acc.mu.Unlock()
s.updateRemoteServer(&m.Server)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"remoteConnsUpdate",
"(",
"sub",
"*",
"subscription",
",",
"subject",
",",
"reply",
"string",
",",
"msg",
"[",
"]",
"byte",
")",
"{",
"if",
"!",
"s",
".",
"eventsRunning",
"(",
")",
"{",
"return",
"\n",
"}",
"\... | // remoteConnsUpdate gets called when we receive a remote update from another server. | [
"remoteConnsUpdate",
"gets",
"called",
"when",
"we",
"receive",
"a",
"remote",
"update",
"from",
"another",
"server",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L622-L665 |
164,326 | nats-io/gnatsd | server/events.go | enableAccountTracking | func (s *Server) enableAccountTracking(a *Account) {
if a == nil || !s.eventsEnabled() {
return
}
// TODO(ik): Generate payload although message may not be sent.
// May need to ensure we do so only if there is a known interest.
// This can get complicated with gateways.
subj := fmt.Sprintf(accConnsReqSubj, a.Name)
reply := fmt.Sprintf(connsRespSubj, s.info.ID)
m := accNumConnsReq{Account: a.Name}
s.sendInternalMsg(subj, reply, &m.Server, &m)
} | go | func (s *Server) enableAccountTracking(a *Account) {
if a == nil || !s.eventsEnabled() {
return
}
// TODO(ik): Generate payload although message may not be sent.
// May need to ensure we do so only if there is a known interest.
// This can get complicated with gateways.
subj := fmt.Sprintf(accConnsReqSubj, a.Name)
reply := fmt.Sprintf(connsRespSubj, s.info.ID)
m := accNumConnsReq{Account: a.Name}
s.sendInternalMsg(subj, reply, &m.Server, &m)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"enableAccountTracking",
"(",
"a",
"*",
"Account",
")",
"{",
"if",
"a",
"==",
"nil",
"||",
"!",
"s",
".",
"eventsEnabled",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// TODO(ik): Generate payload although message may n... | // Setup tracking for this account. This allows us to track globally
// account activity.
// Lock should be held on entry. | [
"Setup",
"tracking",
"for",
"this",
"account",
".",
"This",
"allows",
"us",
"to",
"track",
"globally",
"account",
"activity",
".",
"Lock",
"should",
"be",
"held",
"on",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L670-L683 |
164,327 | nats-io/gnatsd | server/events.go | sendLeafNodeConnect | func (s *Server) sendLeafNodeConnect(a *Account) {
s.mu.Lock()
// If we are not in operator mode, or do not have any gateways defined, this should also be a no-op.
if a == nil || !s.eventsEnabled() || !s.gateway.enabled {
s.mu.Unlock()
return
}
subj := fmt.Sprintf(leafNodeConnectEventSubj, a.Name)
m := accNumConnsReq{Account: a.Name}
s.sendInternalMsg(subj, "", &m.Server, &m)
s.mu.Unlock()
s.switchAccountToInterestMode(a.Name)
} | go | func (s *Server) sendLeafNodeConnect(a *Account) {
s.mu.Lock()
// If we are not in operator mode, or do not have any gateways defined, this should also be a no-op.
if a == nil || !s.eventsEnabled() || !s.gateway.enabled {
s.mu.Unlock()
return
}
subj := fmt.Sprintf(leafNodeConnectEventSubj, a.Name)
m := accNumConnsReq{Account: a.Name}
s.sendInternalMsg(subj, "", &m.Server, &m)
s.mu.Unlock()
s.switchAccountToInterestMode(a.Name)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendLeafNodeConnect",
"(",
"a",
"*",
"Account",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"// If we are not in operator mode, or do not have any gateways defined, this should also be a no-op.",
"if",
"a",
"==",
"ni... | // Event on leaf node connect.
// Lock should NOT be held on entry. | [
"Event",
"on",
"leaf",
"node",
"connect",
".",
"Lock",
"should",
"NOT",
"be",
"held",
"on",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L687-L700 |
164,328 | nats-io/gnatsd | server/events.go | sendAccConnsUpdate | func (s *Server) sendAccConnsUpdate(a *Account, subj string) {
if !s.eventsEnabled() || a == nil || a == s.gacc {
return
}
a.mu.RLock()
// If no limits set, don't update, no need to.
if a.mconns == jwt.NoLimit && a.mleafs == jwt.NoLimit {
a.mu.RUnlock()
return
}
// Build event with account name and number of local clients and leafnodes.
m := AccountNumConns{
Account: a.Name,
Conns: a.numLocalConnections(),
LeafNodes: a.numLocalLeafNodes(),
TotalConns: a.numLocalConnections() + a.numLocalLeafNodes(),
}
a.mu.RUnlock()
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
// Set timer to fire again unless we are at zero.
a.mu.Lock()
if a.numLocalConnections() == 0 {
clearTimer(&a.etmr)
} else {
// Check to see if we have an HB running and update.
if a.ctmr == nil {
a.etmr = time.AfterFunc(eventsHBInterval, func() { s.accConnsUpdate(a) })
} else {
a.etmr.Reset(eventsHBInterval)
}
}
a.mu.Unlock()
} | go | func (s *Server) sendAccConnsUpdate(a *Account, subj string) {
if !s.eventsEnabled() || a == nil || a == s.gacc {
return
}
a.mu.RLock()
// If no limits set, don't update, no need to.
if a.mconns == jwt.NoLimit && a.mleafs == jwt.NoLimit {
a.mu.RUnlock()
return
}
// Build event with account name and number of local clients and leafnodes.
m := AccountNumConns{
Account: a.Name,
Conns: a.numLocalConnections(),
LeafNodes: a.numLocalLeafNodes(),
TotalConns: a.numLocalConnections() + a.numLocalLeafNodes(),
}
a.mu.RUnlock()
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
// Set timer to fire again unless we are at zero.
a.mu.Lock()
if a.numLocalConnections() == 0 {
clearTimer(&a.etmr)
} else {
// Check to see if we have an HB running and update.
if a.ctmr == nil {
a.etmr = time.AfterFunc(eventsHBInterval, func() { s.accConnsUpdate(a) })
} else {
a.etmr.Reset(eventsHBInterval)
}
}
a.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendAccConnsUpdate",
"(",
"a",
"*",
"Account",
",",
"subj",
"string",
")",
"{",
"if",
"!",
"s",
".",
"eventsEnabled",
"(",
")",
"||",
"a",
"==",
"nil",
"||",
"a",
"==",
"s",
".",
"gacc",
"{",
"return",
"\n",... | // sendAccConnsUpdate is called to send out our information on the
// account's local connections.
// Lock should be held on entry. | [
"sendAccConnsUpdate",
"is",
"called",
"to",
"send",
"out",
"our",
"information",
"on",
"the",
"account",
"s",
"local",
"connections",
".",
"Lock",
"should",
"be",
"held",
"on",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L708-L744 |
164,329 | nats-io/gnatsd | server/events.go | accConnsUpdate | func (s *Server) accConnsUpdate(a *Account) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() || a == nil {
return
}
subj := fmt.Sprintf(accConnsEventSubj, a.Name)
s.sendAccConnsUpdate(a, subj)
} | go | func (s *Server) accConnsUpdate(a *Account) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() || a == nil {
return
}
subj := fmt.Sprintf(accConnsEventSubj, a.Name)
s.sendAccConnsUpdate(a, subj)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"accConnsUpdate",
"(",
"a",
"*",
"Account",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"s",
".",
"eventsEnabled",
"(",
")",
"... | // accConnsUpdate is called whenever there is a change to the account's
// number of active connections, or during a heartbeat. | [
"accConnsUpdate",
"is",
"called",
"whenever",
"there",
"is",
"a",
"change",
"to",
"the",
"account",
"s",
"number",
"of",
"active",
"connections",
"or",
"during",
"a",
"heartbeat",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L748-L756 |
164,330 | nats-io/gnatsd | server/events.go | accountConnectEvent | func (s *Server) accountConnectEvent(c *client) {
s.mu.Lock()
if !s.eventsEnabled() {
s.mu.Unlock()
return
}
s.mu.Unlock()
subj := fmt.Sprintf(connectEventSubj, c.acc.Name)
c.mu.Lock()
m := ConnectEventMsg{
Client: ClientInfo{
Start: c.start,
Host: c.host,
ID: c.cid,
Account: accForClient(c),
User: nameForClient(c),
Name: c.opts.Name,
Lang: c.opts.Lang,
Version: c.opts.Version,
},
}
c.mu.Unlock()
s.mu.Lock()
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
s.mu.Unlock()
} | go | func (s *Server) accountConnectEvent(c *client) {
s.mu.Lock()
if !s.eventsEnabled() {
s.mu.Unlock()
return
}
s.mu.Unlock()
subj := fmt.Sprintf(connectEventSubj, c.acc.Name)
c.mu.Lock()
m := ConnectEventMsg{
Client: ClientInfo{
Start: c.start,
Host: c.host,
ID: c.cid,
Account: accForClient(c),
User: nameForClient(c),
Name: c.opts.Name,
Lang: c.opts.Lang,
Version: c.opts.Version,
},
}
c.mu.Unlock()
s.mu.Lock()
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
s.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"accountConnectEvent",
"(",
"c",
"*",
"client",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"!",
"s",
".",
"eventsEnabled",
"(",
")",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"... | // accountConnectEvent will send an account client connect event if there is interest.
// This is a billing event. | [
"accountConnectEvent",
"will",
"send",
"an",
"account",
"client",
"connect",
"event",
"if",
"there",
"is",
"interest",
".",
"This",
"is",
"a",
"billing",
"event",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L760-L788 |
164,331 | nats-io/gnatsd | server/events.go | accountDisconnectEvent | func (s *Server) accountDisconnectEvent(c *client, now time.Time, reason string) {
s.mu.Lock()
gacc := s.gacc
if !s.eventsEnabled() {
s.mu.Unlock()
return
}
s.mu.Unlock()
c.mu.Lock()
// Ignore global account activity
if c.acc == nil || c.acc == gacc {
c.mu.Unlock()
return
}
m := DisconnectEventMsg{
Client: ClientInfo{
Start: c.start,
Stop: &now,
Host: c.host,
ID: c.cid,
Account: accForClient(c),
User: nameForClient(c),
Name: c.opts.Name,
Lang: c.opts.Lang,
Version: c.opts.Version,
RTT: c.getRTT(),
},
Sent: DataStats{
Msgs: c.inMsgs,
Bytes: c.inBytes,
},
Received: DataStats{
Msgs: c.outMsgs,
Bytes: c.outBytes,
},
Reason: reason,
}
c.mu.Unlock()
subj := fmt.Sprintf(disconnectEventSubj, c.acc.Name)
s.mu.Lock()
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
s.mu.Unlock()
} | go | func (s *Server) accountDisconnectEvent(c *client, now time.Time, reason string) {
s.mu.Lock()
gacc := s.gacc
if !s.eventsEnabled() {
s.mu.Unlock()
return
}
s.mu.Unlock()
c.mu.Lock()
// Ignore global account activity
if c.acc == nil || c.acc == gacc {
c.mu.Unlock()
return
}
m := DisconnectEventMsg{
Client: ClientInfo{
Start: c.start,
Stop: &now,
Host: c.host,
ID: c.cid,
Account: accForClient(c),
User: nameForClient(c),
Name: c.opts.Name,
Lang: c.opts.Lang,
Version: c.opts.Version,
RTT: c.getRTT(),
},
Sent: DataStats{
Msgs: c.inMsgs,
Bytes: c.inBytes,
},
Received: DataStats{
Msgs: c.outMsgs,
Bytes: c.outBytes,
},
Reason: reason,
}
c.mu.Unlock()
subj := fmt.Sprintf(disconnectEventSubj, c.acc.Name)
s.mu.Lock()
s.sendInternalMsg(subj, _EMPTY_, &m.Server, &m)
s.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"accountDisconnectEvent",
"(",
"c",
"*",
"client",
",",
"now",
"time",
".",
"Time",
",",
"reason",
"string",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"gacc",
":=",
"s",
".",
"gacc",
"\n",
"if",
... | // accountDisconnectEvent will send an account client disconnect event if there is interest.
// This is a billing event. | [
"accountDisconnectEvent",
"will",
"send",
"an",
"account",
"client",
"disconnect",
"event",
"if",
"there",
"is",
"interest",
".",
"This",
"is",
"a",
"billing",
"event",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L792-L839 |
164,332 | nats-io/gnatsd | server/events.go | sysSubscribe | func (s *Server) sysSubscribe(subject string, cb msgHandler) (*subscription, error) {
if !s.eventsEnabled() {
return nil, ErrNoSysAccount
}
if cb == nil {
return nil, fmt.Errorf("undefined message handler")
}
s.mu.Lock()
sid := strconv.FormatInt(int64(s.sys.sid), 10)
s.sys.subs[sid] = cb
s.sys.sid++
c := s.sys.client
s.mu.Unlock()
// Now create the subscription
if err := c.processSub([]byte(subject + " " + sid)); err != nil {
return nil, err
}
c.mu.Lock()
sub := c.subs[sid]
c.mu.Unlock()
return sub, nil
} | go | func (s *Server) sysSubscribe(subject string, cb msgHandler) (*subscription, error) {
if !s.eventsEnabled() {
return nil, ErrNoSysAccount
}
if cb == nil {
return nil, fmt.Errorf("undefined message handler")
}
s.mu.Lock()
sid := strconv.FormatInt(int64(s.sys.sid), 10)
s.sys.subs[sid] = cb
s.sys.sid++
c := s.sys.client
s.mu.Unlock()
// Now create the subscription
if err := c.processSub([]byte(subject + " " + sid)); err != nil {
return nil, err
}
c.mu.Lock()
sub := c.subs[sid]
c.mu.Unlock()
return sub, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sysSubscribe",
"(",
"subject",
"string",
",",
"cb",
"msgHandler",
")",
"(",
"*",
"subscription",
",",
"error",
")",
"{",
"if",
"!",
"s",
".",
"eventsEnabled",
"(",
")",
"{",
"return",
"nil",
",",
"ErrNoSysAccount"... | // Create an internal subscription. No support for queue groups atm. | [
"Create",
"an",
"internal",
"subscription",
".",
"No",
"support",
"for",
"queue",
"groups",
"atm",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L900-L922 |
164,333 | nats-io/gnatsd | server/events.go | nameForClient | func nameForClient(c *client) string {
if c.user != nil {
return c.user.Nkey
}
return "N/A"
} | go | func nameForClient(c *client) string {
if c.user != nil {
return c.user.Nkey
}
return "N/A"
} | [
"func",
"nameForClient",
"(",
"c",
"*",
"client",
")",
"string",
"{",
"if",
"c",
".",
"user",
"!=",
"nil",
"{",
"return",
"c",
".",
"user",
".",
"Nkey",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Helper to grab name for a client. | [
"Helper",
"to",
"grab",
"name",
"for",
"a",
"client",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L937-L942 |
164,334 | nats-io/gnatsd | server/events.go | accForClient | func accForClient(c *client) string {
if c.acc != nil {
return c.acc.Name
}
return "N/A"
} | go | func accForClient(c *client) string {
if c.acc != nil {
return c.acc.Name
}
return "N/A"
} | [
"func",
"accForClient",
"(",
"c",
"*",
"client",
")",
"string",
"{",
"if",
"c",
".",
"acc",
"!=",
"nil",
"{",
"return",
"c",
".",
"acc",
".",
"Name",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Helper to grab account name for a client. | [
"Helper",
"to",
"grab",
"account",
"name",
"for",
"a",
"client",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L945-L950 |
164,335 | nats-io/gnatsd | server/events.go | clearTimer | func clearTimer(tp **time.Timer) {
if t := *tp; t != nil {
t.Stop()
*tp = nil
}
} | go | func clearTimer(tp **time.Timer) {
if t := *tp; t != nil {
t.Stop()
*tp = nil
}
} | [
"func",
"clearTimer",
"(",
"tp",
"*",
"*",
"time",
".",
"Timer",
")",
"{",
"if",
"t",
":=",
"*",
"tp",
";",
"t",
"!=",
"nil",
"{",
"t",
".",
"Stop",
"(",
")",
"\n",
"*",
"tp",
"=",
"nil",
"\n",
"}",
"\n",
"}"
] | // Helper to clear timers. | [
"Helper",
"to",
"clear",
"timers",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L953-L958 |
164,336 | nats-io/gnatsd | server/events.go | wrapChk | func (s *Server) wrapChk(f func()) func() {
return func() {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() {
return
}
f()
}
} | go | func (s *Server) wrapChk(f func()) func() {
return func() {
s.mu.Lock()
defer s.mu.Unlock()
if !s.eventsEnabled() {
return
}
f()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"wrapChk",
"(",
"f",
"func",
"(",
")",
")",
"func",
"(",
")",
"{",
"return",
"func",
"(",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
... | // Helper function to wrap functions with common test
// to lock server and return if events not enabled. | [
"Helper",
"function",
"to",
"wrap",
"functions",
"with",
"common",
"test",
"to",
"lock",
"server",
"and",
"return",
"if",
"events",
"not",
"enabled",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/events.go#L962-L971 |
164,337 | nats-io/gnatsd | logger/syslog.go | GetSysLoggerTag | func GetSysLoggerTag() string {
procName := os.Args[0]
if strings.ContainsRune(procName, os.PathSeparator) {
parts := strings.FieldsFunc(procName, func(c rune) bool {
return c == os.PathSeparator
})
procName = parts[len(parts)-1]
}
return procName
} | go | func GetSysLoggerTag() string {
procName := os.Args[0]
if strings.ContainsRune(procName, os.PathSeparator) {
parts := strings.FieldsFunc(procName, func(c rune) bool {
return c == os.PathSeparator
})
procName = parts[len(parts)-1]
}
return procName
} | [
"func",
"GetSysLoggerTag",
"(",
")",
"string",
"{",
"procName",
":=",
"os",
".",
"Args",
"[",
"0",
"]",
"\n",
"if",
"strings",
".",
"ContainsRune",
"(",
"procName",
",",
"os",
".",
"PathSeparator",
")",
"{",
"parts",
":=",
"strings",
".",
"FieldsFunc",
... | // GetSysLoggerTag generates the tag name for use in syslog statements. If
// the executable is linked, the name of the link will be used as the tag,
// otherwise, the name of the executable is used. "gnatsd" is the default
// for the NATS server. | [
"GetSysLoggerTag",
"generates",
"the",
"tag",
"name",
"for",
"use",
"in",
"syslog",
"statements",
".",
"If",
"the",
"executable",
"is",
"linked",
"the",
"name",
"of",
"the",
"link",
"will",
"be",
"used",
"as",
"the",
"tag",
"otherwise",
"the",
"name",
"of"... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/logger/syslog.go#L42-L51 |
164,338 | nats-io/gnatsd | logger/syslog.go | NewSysLogger | func NewSysLogger(debug, trace bool) *SysLogger {
w, err := syslog.New(syslog.LOG_DAEMON|syslog.LOG_NOTICE, GetSysLoggerTag())
if err != nil {
log.Fatalf("error connecting to syslog: %q", err.Error())
}
return &SysLogger{
writer: w,
debug: debug,
trace: trace,
}
} | go | func NewSysLogger(debug, trace bool) *SysLogger {
w, err := syslog.New(syslog.LOG_DAEMON|syslog.LOG_NOTICE, GetSysLoggerTag())
if err != nil {
log.Fatalf("error connecting to syslog: %q", err.Error())
}
return &SysLogger{
writer: w,
debug: debug,
trace: trace,
}
} | [
"func",
"NewSysLogger",
"(",
"debug",
",",
"trace",
"bool",
")",
"*",
"SysLogger",
"{",
"w",
",",
"err",
":=",
"syslog",
".",
"New",
"(",
"syslog",
".",
"LOG_DAEMON",
"|",
"syslog",
".",
"LOG_NOTICE",
",",
"GetSysLoggerTag",
"(",
")",
")",
"\n",
"if",
... | // NewSysLogger creates a new system logger | [
"NewSysLogger",
"creates",
"a",
"new",
"system",
"logger"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/logger/syslog.go#L54-L65 |
164,339 | nats-io/gnatsd | logger/syslog.go | NewRemoteSysLogger | func NewRemoteSysLogger(fqn string, debug, trace bool) *SysLogger {
network, addr := getNetworkAndAddr(fqn)
w, err := syslog.Dial(network, addr, syslog.LOG_DEBUG, GetSysLoggerTag())
if err != nil {
log.Fatalf("error connecting to syslog: %q", err.Error())
}
return &SysLogger{
writer: w,
debug: debug,
trace: trace,
}
} | go | func NewRemoteSysLogger(fqn string, debug, trace bool) *SysLogger {
network, addr := getNetworkAndAddr(fqn)
w, err := syslog.Dial(network, addr, syslog.LOG_DEBUG, GetSysLoggerTag())
if err != nil {
log.Fatalf("error connecting to syslog: %q", err.Error())
}
return &SysLogger{
writer: w,
debug: debug,
trace: trace,
}
} | [
"func",
"NewRemoteSysLogger",
"(",
"fqn",
"string",
",",
"debug",
",",
"trace",
"bool",
")",
"*",
"SysLogger",
"{",
"network",
",",
"addr",
":=",
"getNetworkAndAddr",
"(",
"fqn",
")",
"\n",
"w",
",",
"err",
":=",
"syslog",
".",
"Dial",
"(",
"network",
... | // NewRemoteSysLogger creates a new remote system logger | [
"NewRemoteSysLogger",
"creates",
"a",
"new",
"remote",
"system",
"logger"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/logger/syslog.go#L68-L80 |
164,340 | nats-io/gnatsd | server/signal.go | ProcessSignal | func ProcessSignal(command Command, pidStr string) error {
var pid int
if pidStr == "" {
pids, err := resolvePids()
if err != nil {
return err
}
if len(pids) == 0 {
return fmt.Errorf("no %s processes running", processName)
}
if len(pids) > 1 {
errStr := fmt.Sprintf("multiple %s processes running:\n", processName)
prefix := ""
for _, p := range pids {
errStr += fmt.Sprintf("%s%d", prefix, p)
prefix = "\n"
}
return errors.New(errStr)
}
pid = pids[0]
} else {
p, err := strconv.Atoi(pidStr)
if err != nil {
return fmt.Errorf("invalid pid: %s", pidStr)
}
pid = p
}
var err error
switch command {
case CommandStop:
err = kill(pid, syscall.SIGKILL)
case CommandQuit:
err = kill(pid, syscall.SIGINT)
case CommandReopen:
err = kill(pid, syscall.SIGUSR1)
case CommandReload:
err = kill(pid, syscall.SIGHUP)
case commandLDMode:
err = kill(pid, syscall.SIGUSR2)
default:
err = fmt.Errorf("unknown signal %q", command)
}
return err
} | go | func ProcessSignal(command Command, pidStr string) error {
var pid int
if pidStr == "" {
pids, err := resolvePids()
if err != nil {
return err
}
if len(pids) == 0 {
return fmt.Errorf("no %s processes running", processName)
}
if len(pids) > 1 {
errStr := fmt.Sprintf("multiple %s processes running:\n", processName)
prefix := ""
for _, p := range pids {
errStr += fmt.Sprintf("%s%d", prefix, p)
prefix = "\n"
}
return errors.New(errStr)
}
pid = pids[0]
} else {
p, err := strconv.Atoi(pidStr)
if err != nil {
return fmt.Errorf("invalid pid: %s", pidStr)
}
pid = p
}
var err error
switch command {
case CommandStop:
err = kill(pid, syscall.SIGKILL)
case CommandQuit:
err = kill(pid, syscall.SIGINT)
case CommandReopen:
err = kill(pid, syscall.SIGUSR1)
case CommandReload:
err = kill(pid, syscall.SIGHUP)
case commandLDMode:
err = kill(pid, syscall.SIGUSR2)
default:
err = fmt.Errorf("unknown signal %q", command)
}
return err
} | [
"func",
"ProcessSignal",
"(",
"command",
"Command",
",",
"pidStr",
"string",
")",
"error",
"{",
"var",
"pid",
"int",
"\n",
"if",
"pidStr",
"==",
"\"",
"\"",
"{",
"pids",
",",
"err",
":=",
"resolvePids",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
... | // ProcessSignal sends the given signal command to the given process. If pidStr
// is empty, this will send the signal to the single running instance of
// gnatsd. If multiple instances are running, it returns an error. This returns
// an error if the given process is not running or the command is invalid. | [
"ProcessSignal",
"sends",
"the",
"given",
"signal",
"command",
"to",
"the",
"given",
"process",
".",
"If",
"pidStr",
"is",
"empty",
"this",
"will",
"send",
"the",
"signal",
"to",
"the",
"single",
"running",
"instance",
"of",
"gnatsd",
".",
"If",
"multiple",
... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/signal.go#L76-L120 |
164,341 | nats-io/gnatsd | server/signal.go | resolvePids | func resolvePids() ([]int, error) {
// If pgrep isn't available, this will just bail out and the user will be
// required to specify a pid.
output, err := pgrep()
if err != nil {
switch err.(type) {
case *exec.ExitError:
// ExitError indicates non-zero exit code, meaning no processes
// found.
break
default:
return nil, errors.New("unable to resolve pid, try providing one")
}
}
var (
myPid = os.Getpid()
pidStrs = strings.Split(string(output), "\n")
pids = make([]int, 0, len(pidStrs))
)
for _, pidStr := range pidStrs {
if pidStr == "" {
continue
}
pid, err := strconv.Atoi(pidStr)
if err != nil {
return nil, errors.New("unable to resolve pid, try providing one")
}
// Ignore the current process.
if pid == myPid {
continue
}
pids = append(pids, pid)
}
return pids, nil
} | go | func resolvePids() ([]int, error) {
// If pgrep isn't available, this will just bail out and the user will be
// required to specify a pid.
output, err := pgrep()
if err != nil {
switch err.(type) {
case *exec.ExitError:
// ExitError indicates non-zero exit code, meaning no processes
// found.
break
default:
return nil, errors.New("unable to resolve pid, try providing one")
}
}
var (
myPid = os.Getpid()
pidStrs = strings.Split(string(output), "\n")
pids = make([]int, 0, len(pidStrs))
)
for _, pidStr := range pidStrs {
if pidStr == "" {
continue
}
pid, err := strconv.Atoi(pidStr)
if err != nil {
return nil, errors.New("unable to resolve pid, try providing one")
}
// Ignore the current process.
if pid == myPid {
continue
}
pids = append(pids, pid)
}
return pids, nil
} | [
"func",
"resolvePids",
"(",
")",
"(",
"[",
"]",
"int",
",",
"error",
")",
"{",
"// If pgrep isn't available, this will just bail out and the user will be",
"// required to specify a pid.",
"output",
",",
"err",
":=",
"pgrep",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil"... | // resolvePids returns the pids for all running gnatsd processes. | [
"resolvePids",
"returns",
"the",
"pids",
"for",
"all",
"running",
"gnatsd",
"processes",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/signal.go#L123-L157 |
164,342 | nats-io/gnatsd | conf/lex.go | lexTop | func lexTop(lx *lexer) stateFn {
r := lx.next()
if unicode.IsSpace(r) {
return lexSkip(lx, lexTop)
}
switch r {
case topOptStart:
return lexSkip(lx, lexTop)
case commentHashStart:
lx.push(lexTop)
return lexCommentStart
case commentSlashStart:
rn := lx.next()
if rn == commentSlashStart {
lx.push(lexTop)
return lexCommentStart
}
lx.backup()
fallthrough
case eof:
if lx.pos > lx.start {
return lx.errorf("Unexpected EOF.")
}
lx.emit(itemEOF)
return nil
}
// At this point, the only valid item can be a key, so we back up
// and let the key lexer do the rest.
lx.backup()
lx.push(lexTopValueEnd)
return lexKeyStart
} | go | func lexTop(lx *lexer) stateFn {
r := lx.next()
if unicode.IsSpace(r) {
return lexSkip(lx, lexTop)
}
switch r {
case topOptStart:
return lexSkip(lx, lexTop)
case commentHashStart:
lx.push(lexTop)
return lexCommentStart
case commentSlashStart:
rn := lx.next()
if rn == commentSlashStart {
lx.push(lexTop)
return lexCommentStart
}
lx.backup()
fallthrough
case eof:
if lx.pos > lx.start {
return lx.errorf("Unexpected EOF.")
}
lx.emit(itemEOF)
return nil
}
// At this point, the only valid item can be a key, so we back up
// and let the key lexer do the rest.
lx.backup()
lx.push(lexTopValueEnd)
return lexKeyStart
} | [
"func",
"lexTop",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"if",
"unicode",
".",
"IsSpace",
"(",
"r",
")",
"{",
"return",
"lexSkip",
"(",
"lx",
",",
"lexTop",
")",
"\n",
"}",
"\n\n",
"switch",
... | // lexTop consumes elements at the top level of data structure. | [
"lexTop",
"consumes",
"elements",
"at",
"the",
"top",
"level",
"of",
"data",
"structure",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L257-L290 |
164,343 | nats-io/gnatsd | conf/lex.go | lexTopValueEnd | func lexTopValueEnd(lx *lexer) stateFn {
r := lx.next()
switch {
case r == commentHashStart:
// a comment will read to a new line for us.
lx.push(lexTop)
return lexCommentStart
case r == commentSlashStart:
rn := lx.next()
if rn == commentSlashStart {
lx.push(lexTop)
return lexCommentStart
}
lx.backup()
fallthrough
case isWhitespace(r):
return lexTopValueEnd
case isNL(r) || r == eof || r == optValTerm || r == topOptValTerm || r == topOptTerm:
lx.ignore()
return lexTop
}
return lx.errorf("Expected a top-level value to end with a new line, "+
"comment or EOF, but got '%v' instead.", r)
} | go | func lexTopValueEnd(lx *lexer) stateFn {
r := lx.next()
switch {
case r == commentHashStart:
// a comment will read to a new line for us.
lx.push(lexTop)
return lexCommentStart
case r == commentSlashStart:
rn := lx.next()
if rn == commentSlashStart {
lx.push(lexTop)
return lexCommentStart
}
lx.backup()
fallthrough
case isWhitespace(r):
return lexTopValueEnd
case isNL(r) || r == eof || r == optValTerm || r == topOptValTerm || r == topOptTerm:
lx.ignore()
return lexTop
}
return lx.errorf("Expected a top-level value to end with a new line, "+
"comment or EOF, but got '%v' instead.", r)
} | [
"func",
"lexTopValueEnd",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"switch",
"{",
"case",
"r",
"==",
"commentHashStart",
":",
"// a comment will read to a new line for us.",
"lx",
".",
"push",
"(",
"lexTop",... | // lexTopValueEnd is entered whenever a top-level value has been consumed.
// It must see only whitespace, and will turn back to lexTop upon a new line.
// If it sees EOF, it will quit the lexer successfully. | [
"lexTopValueEnd",
"is",
"entered",
"whenever",
"a",
"top",
"-",
"level",
"value",
"has",
"been",
"consumed",
".",
"It",
"must",
"see",
"only",
"whitespace",
"and",
"will",
"turn",
"back",
"to",
"lexTop",
"upon",
"a",
"new",
"line",
".",
"If",
"it",
"sees... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L295-L318 |
164,344 | nats-io/gnatsd | conf/lex.go | keyCheckKeyword | func (lx *lexer) keyCheckKeyword(fallThrough, push stateFn) stateFn {
key := strings.ToLower(lx.input[lx.start:lx.pos])
switch key {
case "include":
lx.ignore()
if push != nil {
lx.push(push)
}
return lexIncludeStart
}
lx.emit(itemKey)
return fallThrough
} | go | func (lx *lexer) keyCheckKeyword(fallThrough, push stateFn) stateFn {
key := strings.ToLower(lx.input[lx.start:lx.pos])
switch key {
case "include":
lx.ignore()
if push != nil {
lx.push(push)
}
return lexIncludeStart
}
lx.emit(itemKey)
return fallThrough
} | [
"func",
"(",
"lx",
"*",
"lexer",
")",
"keyCheckKeyword",
"(",
"fallThrough",
",",
"push",
"stateFn",
")",
"stateFn",
"{",
"key",
":=",
"strings",
".",
"ToLower",
"(",
"lx",
".",
"input",
"[",
"lx",
".",
"start",
":",
"lx",
".",
"pos",
"]",
")",
"\n... | // keyCheckKeyword will check for reserved keywords as the key value when the key is
// separated with a space. | [
"keyCheckKeyword",
"will",
"check",
"for",
"reserved",
"keywords",
"as",
"the",
"key",
"value",
"when",
"the",
"key",
"is",
"separated",
"with",
"a",
"space",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L380-L392 |
164,345 | nats-io/gnatsd | conf/lex.go | lexIncludeStart | func lexIncludeStart(lx *lexer) stateFn {
r := lx.next()
if isWhitespace(r) {
return lexSkip(lx, lexIncludeStart)
}
lx.backup()
return lexInclude
} | go | func lexIncludeStart(lx *lexer) stateFn {
r := lx.next()
if isWhitespace(r) {
return lexSkip(lx, lexIncludeStart)
}
lx.backup()
return lexInclude
} | [
"func",
"lexIncludeStart",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"if",
"isWhitespace",
"(",
"r",
")",
"{",
"return",
"lexSkip",
"(",
"lx",
",",
"lexIncludeStart",
")",
"\n",
"}",
"\n",
"lx",
"."... | // lexIncludeStart will consume the whitespace til the start of the value. | [
"lexIncludeStart",
"will",
"consume",
"the",
"whitespace",
"til",
"the",
"start",
"of",
"the",
"value",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L395-L402 |
164,346 | nats-io/gnatsd | conf/lex.go | lexIncludeQuotedString | func lexIncludeQuotedString(lx *lexer) stateFn {
r := lx.next()
switch {
case r == sqStringEnd:
lx.backup()
lx.emit(itemInclude)
lx.next()
lx.ignore()
return lx.pop()
}
return lexIncludeQuotedString
} | go | func lexIncludeQuotedString(lx *lexer) stateFn {
r := lx.next()
switch {
case r == sqStringEnd:
lx.backup()
lx.emit(itemInclude)
lx.next()
lx.ignore()
return lx.pop()
}
return lexIncludeQuotedString
} | [
"func",
"lexIncludeQuotedString",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"switch",
"{",
"case",
"r",
"==",
"sqStringEnd",
":",
"lx",
".",
"backup",
"(",
")",
"\n",
"lx",
".",
"emit",
"(",
"itemIn... | // lexIncludeQuotedString consumes the inner contents of a string. It assumes that the
// beginning '"' has already been consumed and ignored. It will not interpret any
// internal contents. | [
"lexIncludeQuotedString",
"consumes",
"the",
"inner",
"contents",
"of",
"a",
"string",
".",
"It",
"assumes",
"that",
"the",
"beginning",
"has",
"already",
"been",
"consumed",
"and",
"ignored",
".",
"It",
"will",
"not",
"interpret",
"any",
"internal",
"contents",... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L407-L418 |
164,347 | nats-io/gnatsd | conf/lex.go | lexIncludeDubQuotedString | func lexIncludeDubQuotedString(lx *lexer) stateFn {
r := lx.next()
switch {
case r == dqStringEnd:
lx.backup()
lx.emit(itemInclude)
lx.next()
lx.ignore()
return lx.pop()
}
return lexIncludeDubQuotedString
} | go | func lexIncludeDubQuotedString(lx *lexer) stateFn {
r := lx.next()
switch {
case r == dqStringEnd:
lx.backup()
lx.emit(itemInclude)
lx.next()
lx.ignore()
return lx.pop()
}
return lexIncludeDubQuotedString
} | [
"func",
"lexIncludeDubQuotedString",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"switch",
"{",
"case",
"r",
"==",
"dqStringEnd",
":",
"lx",
".",
"backup",
"(",
")",
"\n",
"lx",
".",
"emit",
"(",
"ite... | // lexIncludeDubQuotedString consumes the inner contents of a string. It assumes that the
// beginning '"' has already been consumed and ignored. It will not interpret any
// internal contents. | [
"lexIncludeDubQuotedString",
"consumes",
"the",
"inner",
"contents",
"of",
"a",
"string",
".",
"It",
"assumes",
"that",
"the",
"beginning",
"has",
"already",
"been",
"consumed",
"and",
"ignored",
".",
"It",
"will",
"not",
"interpret",
"any",
"internal",
"content... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L423-L434 |
164,348 | nats-io/gnatsd | conf/lex.go | lexIncludeString | func lexIncludeString(lx *lexer) stateFn {
r := lx.next()
switch {
case isNL(r) || r == eof || r == optValTerm || r == mapEnd || isWhitespace(r):
lx.backup()
lx.emit(itemInclude)
return lx.pop()
case r == sqStringEnd:
lx.backup()
lx.emit(itemInclude)
lx.next()
lx.ignore()
return lx.pop()
}
return lexIncludeString
} | go | func lexIncludeString(lx *lexer) stateFn {
r := lx.next()
switch {
case isNL(r) || r == eof || r == optValTerm || r == mapEnd || isWhitespace(r):
lx.backup()
lx.emit(itemInclude)
return lx.pop()
case r == sqStringEnd:
lx.backup()
lx.emit(itemInclude)
lx.next()
lx.ignore()
return lx.pop()
}
return lexIncludeString
} | [
"func",
"lexIncludeString",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"switch",
"{",
"case",
"isNL",
"(",
"r",
")",
"||",
"r",
"==",
"eof",
"||",
"r",
"==",
"optValTerm",
"||",
"r",
"==",
"mapEnd"... | // lexIncludeString consumes the inner contents of a raw string. | [
"lexIncludeString",
"consumes",
"the",
"inner",
"contents",
"of",
"a",
"raw",
"string",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L437-L452 |
164,349 | nats-io/gnatsd | conf/lex.go | lexInclude | func lexInclude(lx *lexer) stateFn {
r := lx.next()
switch {
case r == sqStringStart:
lx.ignore() // ignore the " or '
return lexIncludeQuotedString
case r == dqStringStart:
lx.ignore() // ignore the " or '
return lexIncludeDubQuotedString
case r == arrayStart:
return lx.errorf("Expected include value but found start of an array")
case r == mapStart:
return lx.errorf("Expected include value but found start of a map")
case r == blockStart:
return lx.errorf("Expected include value but found start of a block")
case unicode.IsDigit(r), r == '-':
return lx.errorf("Expected include value but found start of a number")
case r == '\\':
return lx.errorf("Expected include value but found escape sequence")
case isNL(r):
return lx.errorf("Expected include value but found new line")
}
lx.backup()
return lexIncludeString
} | go | func lexInclude(lx *lexer) stateFn {
r := lx.next()
switch {
case r == sqStringStart:
lx.ignore() // ignore the " or '
return lexIncludeQuotedString
case r == dqStringStart:
lx.ignore() // ignore the " or '
return lexIncludeDubQuotedString
case r == arrayStart:
return lx.errorf("Expected include value but found start of an array")
case r == mapStart:
return lx.errorf("Expected include value but found start of a map")
case r == blockStart:
return lx.errorf("Expected include value but found start of a block")
case unicode.IsDigit(r), r == '-':
return lx.errorf("Expected include value but found start of a number")
case r == '\\':
return lx.errorf("Expected include value but found escape sequence")
case isNL(r):
return lx.errorf("Expected include value but found new line")
}
lx.backup()
return lexIncludeString
} | [
"func",
"lexInclude",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"switch",
"{",
"case",
"r",
"==",
"sqStringStart",
":",
"lx",
".",
"ignore",
"(",
")",
"// ignore the \" or '",
"\n",
"return",
"lexInclud... | // lexInclude will consume the include value. | [
"lexInclude",
"will",
"consume",
"the",
"include",
"value",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L455-L479 |
164,350 | nats-io/gnatsd | conf/lex.go | lexArrayValueEnd | func lexArrayValueEnd(lx *lexer) stateFn {
r := lx.next()
switch {
case isWhitespace(r):
return lexSkip(lx, lexArrayValueEnd)
case r == commentHashStart:
lx.push(lexArrayValueEnd)
return lexCommentStart
case r == commentSlashStart:
rn := lx.next()
if rn == commentSlashStart {
lx.push(lexArrayValueEnd)
return lexCommentStart
}
lx.backup()
fallthrough
case r == arrayValTerm || isNL(r):
return lexSkip(lx, lexArrayValue) // Move onto next
case r == arrayEnd:
return lexArrayEnd
}
return lx.errorf("Expected an array value terminator %q or an array "+
"terminator %q, but got '%v' instead.", arrayValTerm, arrayEnd, r)
} | go | func lexArrayValueEnd(lx *lexer) stateFn {
r := lx.next()
switch {
case isWhitespace(r):
return lexSkip(lx, lexArrayValueEnd)
case r == commentHashStart:
lx.push(lexArrayValueEnd)
return lexCommentStart
case r == commentSlashStart:
rn := lx.next()
if rn == commentSlashStart {
lx.push(lexArrayValueEnd)
return lexCommentStart
}
lx.backup()
fallthrough
case r == arrayValTerm || isNL(r):
return lexSkip(lx, lexArrayValue) // Move onto next
case r == arrayEnd:
return lexArrayEnd
}
return lx.errorf("Expected an array value terminator %q or an array "+
"terminator %q, but got '%v' instead.", arrayValTerm, arrayEnd, r)
} | [
"func",
"lexArrayValueEnd",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"switch",
"{",
"case",
"isWhitespace",
"(",
"r",
")",
":",
"return",
"lexSkip",
"(",
"lx",
",",
"lexArrayValueEnd",
")",
"\n",
"ca... | // lexArrayValueEnd consumes the cruft between values of an array. Namely,
// it ignores whitespace and expects either a ',' or a ']'. | [
"lexArrayValueEnd",
"consumes",
"the",
"cruft",
"between",
"values",
"of",
"an",
"array",
".",
"Namely",
"it",
"ignores",
"whitespace",
"and",
"expects",
"either",
"a",
"or",
"a",
"]",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L592-L615 |
164,351 | nats-io/gnatsd | conf/lex.go | lexMapValue | func lexMapValue(lx *lexer) stateFn {
r := lx.next()
switch {
case unicode.IsSpace(r):
return lexSkip(lx, lexMapValue)
case r == mapValTerm:
return lx.errorf("Unexpected map value terminator %q.", mapValTerm)
case r == mapEnd:
return lexSkip(lx, lexMapEnd)
}
lx.backup()
lx.push(lexMapValueEnd)
return lexValue
} | go | func lexMapValue(lx *lexer) stateFn {
r := lx.next()
switch {
case unicode.IsSpace(r):
return lexSkip(lx, lexMapValue)
case r == mapValTerm:
return lx.errorf("Unexpected map value terminator %q.", mapValTerm)
case r == mapEnd:
return lexSkip(lx, lexMapEnd)
}
lx.backup()
lx.push(lexMapValueEnd)
return lexValue
} | [
"func",
"lexMapValue",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"switch",
"{",
"case",
"unicode",
".",
"IsSpace",
"(",
"r",
")",
":",
"return",
"lexSkip",
"(",
"lx",
",",
"lexMapValue",
")",
"\n",
... | // lexMapValue consumes one value in a map. It assumes that '{' or ','
// have already been consumed. All whitespace and new lines are ignored.
// Map values can be separated by ',' or simple NLs. | [
"lexMapValue",
"consumes",
"one",
"value",
"in",
"a",
"map",
".",
"It",
"assumes",
"that",
"{",
"or",
"have",
"already",
"been",
"consumed",
".",
"All",
"whitespace",
"and",
"new",
"lines",
"are",
"ignored",
".",
"Map",
"values",
"can",
"be",
"separated",
... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L726-L739 |
164,352 | nats-io/gnatsd | conf/lex.go | lexMapValueEnd | func lexMapValueEnd(lx *lexer) stateFn {
r := lx.next()
switch {
case isWhitespace(r):
return lexSkip(lx, lexMapValueEnd)
case r == commentHashStart:
lx.push(lexMapValueEnd)
return lexCommentStart
case r == commentSlashStart:
rn := lx.next()
if rn == commentSlashStart {
lx.push(lexMapValueEnd)
return lexCommentStart
}
lx.backup()
fallthrough
case r == optValTerm || r == mapValTerm || isNL(r):
return lexSkip(lx, lexMapKeyStart) // Move onto next
case r == mapEnd:
return lexSkip(lx, lexMapEnd)
}
return lx.errorf("Expected a map value terminator %q or a map "+
"terminator %q, but got '%v' instead.", mapValTerm, mapEnd, r)
} | go | func lexMapValueEnd(lx *lexer) stateFn {
r := lx.next()
switch {
case isWhitespace(r):
return lexSkip(lx, lexMapValueEnd)
case r == commentHashStart:
lx.push(lexMapValueEnd)
return lexCommentStart
case r == commentSlashStart:
rn := lx.next()
if rn == commentSlashStart {
lx.push(lexMapValueEnd)
return lexCommentStart
}
lx.backup()
fallthrough
case r == optValTerm || r == mapValTerm || isNL(r):
return lexSkip(lx, lexMapKeyStart) // Move onto next
case r == mapEnd:
return lexSkip(lx, lexMapEnd)
}
return lx.errorf("Expected a map value terminator %q or a map "+
"terminator %q, but got '%v' instead.", mapValTerm, mapEnd, r)
} | [
"func",
"lexMapValueEnd",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"switch",
"{",
"case",
"isWhitespace",
"(",
"r",
")",
":",
"return",
"lexSkip",
"(",
"lx",
",",
"lexMapValueEnd",
")",
"\n",
"case",... | // lexMapValueEnd consumes the cruft between values of a map. Namely,
// it ignores whitespace and expects either a ',' or a '}'. | [
"lexMapValueEnd",
"consumes",
"the",
"cruft",
"between",
"values",
"of",
"a",
"map",
".",
"Namely",
"it",
"ignores",
"whitespace",
"and",
"expects",
"either",
"a",
"or",
"a",
"}",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L743-L766 |
164,353 | nats-io/gnatsd | conf/lex.go | lexMapEnd | func lexMapEnd(lx *lexer) stateFn {
lx.ignore()
lx.emit(itemMapEnd)
return lx.pop()
} | go | func lexMapEnd(lx *lexer) stateFn {
lx.ignore()
lx.emit(itemMapEnd)
return lx.pop()
} | [
"func",
"lexMapEnd",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"lx",
".",
"ignore",
"(",
")",
"\n",
"lx",
".",
"emit",
"(",
"itemMapEnd",
")",
"\n",
"return",
"lx",
".",
"pop",
"(",
")",
"\n",
"}"
] | // lexMapEnd finishes the lexing of a map. It assumes that a '}' has
// just been consumed. | [
"lexMapEnd",
"finishes",
"the",
"lexing",
"of",
"a",
"map",
".",
"It",
"assumes",
"that",
"a",
"}",
"has",
"just",
"been",
"consumed",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L770-L774 |
164,354 | nats-io/gnatsd | conf/lex.go | isBool | func (lx *lexer) isBool() bool {
str := strings.ToLower(lx.input[lx.start:lx.pos])
return str == "true" || str == "false" ||
str == "on" || str == "off" ||
str == "yes" || str == "no"
} | go | func (lx *lexer) isBool() bool {
str := strings.ToLower(lx.input[lx.start:lx.pos])
return str == "true" || str == "false" ||
str == "on" || str == "off" ||
str == "yes" || str == "no"
} | [
"func",
"(",
"lx",
"*",
"lexer",
")",
"isBool",
"(",
")",
"bool",
"{",
"str",
":=",
"strings",
".",
"ToLower",
"(",
"lx",
".",
"input",
"[",
"lx",
".",
"start",
":",
"lx",
".",
"pos",
"]",
")",
"\n",
"return",
"str",
"==",
"\"",
"\"",
"||",
"... | // Checks if the unquoted string was actually a boolean | [
"Checks",
"if",
"the",
"unquoted",
"string",
"was",
"actually",
"a",
"boolean"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L777-L782 |
164,355 | nats-io/gnatsd | conf/lex.go | lexString | func lexString(lx *lexer) stateFn {
r := lx.next()
switch {
case r == '\\':
lx.addCurrentStringPart(1)
return lexStringEscape
// Termination of non-quoted strings
case isNL(r) || r == eof || r == optValTerm ||
r == arrayValTerm || r == arrayEnd || r == mapEnd ||
isWhitespace(r):
lx.backup()
if lx.hasEscapedParts() {
lx.emitString()
} else if lx.isBool() {
lx.emit(itemBool)
} else if lx.isVariable() {
lx.emit(itemVariable)
} else {
lx.emitString()
}
return lx.pop()
case r == sqStringEnd:
lx.backup()
lx.emitString()
lx.next()
lx.ignore()
return lx.pop()
}
return lexString
} | go | func lexString(lx *lexer) stateFn {
r := lx.next()
switch {
case r == '\\':
lx.addCurrentStringPart(1)
return lexStringEscape
// Termination of non-quoted strings
case isNL(r) || r == eof || r == optValTerm ||
r == arrayValTerm || r == arrayEnd || r == mapEnd ||
isWhitespace(r):
lx.backup()
if lx.hasEscapedParts() {
lx.emitString()
} else if lx.isBool() {
lx.emit(itemBool)
} else if lx.isVariable() {
lx.emit(itemVariable)
} else {
lx.emitString()
}
return lx.pop()
case r == sqStringEnd:
lx.backup()
lx.emitString()
lx.next()
lx.ignore()
return lx.pop()
}
return lexString
} | [
"func",
"lexString",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"switch",
"{",
"case",
"r",
"==",
"'\\\\'",
":",
"lx",
".",
"addCurrentStringPart",
"(",
"1",
")",
"\n",
"return",
"lexStringEscape",
"\n... | // lexString consumes the inner contents of a raw string. | [
"lexString",
"consumes",
"the",
"inner",
"contents",
"of",
"a",
"raw",
"string",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L841-L871 |
164,356 | nats-io/gnatsd | conf/lex.go | lexDateAfterYear | func lexDateAfterYear(lx *lexer) stateFn {
formats := []rune{
// digits are '0'.
// everything else is direct equality.
'0', '0', '-', '0', '0',
'T',
'0', '0', ':', '0', '0', ':', '0', '0',
'Z',
}
for _, f := range formats {
r := lx.next()
if f == '0' {
if !unicode.IsDigit(r) {
return lx.errorf("Expected digit in ISO8601 datetime, "+
"but found '%v' instead.", r)
}
} else if f != r {
return lx.errorf("Expected '%v' in ISO8601 datetime, "+
"but found '%v' instead.", f, r)
}
}
lx.emit(itemDatetime)
return lx.pop()
} | go | func lexDateAfterYear(lx *lexer) stateFn {
formats := []rune{
// digits are '0'.
// everything else is direct equality.
'0', '0', '-', '0', '0',
'T',
'0', '0', ':', '0', '0', ':', '0', '0',
'Z',
}
for _, f := range formats {
r := lx.next()
if f == '0' {
if !unicode.IsDigit(r) {
return lx.errorf("Expected digit in ISO8601 datetime, "+
"but found '%v' instead.", r)
}
} else if f != r {
return lx.errorf("Expected '%v' in ISO8601 datetime, "+
"but found '%v' instead.", f, r)
}
}
lx.emit(itemDatetime)
return lx.pop()
} | [
"func",
"lexDateAfterYear",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"formats",
":=",
"[",
"]",
"rune",
"{",
"// digits are '0'.",
"// everything else is direct equality.",
"'0'",
",",
"'0'",
",",
"'-'",
",",
"'0'",
",",
"'0'",
",",
"'T'",
",",
"'0'",
... | // lexDateAfterYear consumes a full Zulu Datetime in ISO8601 format.
// It assumes that "YYYY-" has already been consumed. | [
"lexDateAfterYear",
"consumes",
"a",
"full",
"Zulu",
"Datetime",
"in",
"ISO8601",
"format",
".",
"It",
"assumes",
"that",
"YYYY",
"-",
"has",
"already",
"been",
"consumed",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L1008-L1031 |
164,357 | nats-io/gnatsd | conf/lex.go | lexNegNumber | func lexNegNumber(lx *lexer) stateFn {
r := lx.next()
switch {
case unicode.IsDigit(r):
return lexNegNumber
case r == '.':
return lexFloatStart
case isNumberSuffix(r):
return lexConvenientNumber
}
lx.backup()
lx.emit(itemInteger)
return lx.pop()
} | go | func lexNegNumber(lx *lexer) stateFn {
r := lx.next()
switch {
case unicode.IsDigit(r):
return lexNegNumber
case r == '.':
return lexFloatStart
case isNumberSuffix(r):
return lexConvenientNumber
}
lx.backup()
lx.emit(itemInteger)
return lx.pop()
} | [
"func",
"lexNegNumber",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"r",
":=",
"lx",
".",
"next",
"(",
")",
"\n",
"switch",
"{",
"case",
"unicode",
".",
"IsDigit",
"(",
"r",
")",
":",
"return",
"lexNegNumber",
"\n",
"case",
"r",
"==",
"'.'",
":",... | // lexNumber consumes a negative integer or a float after seeing the first digit. | [
"lexNumber",
"consumes",
"a",
"negative",
"integer",
"or",
"a",
"float",
"after",
"seeing",
"the",
"first",
"digit",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L1049-L1062 |
164,358 | nats-io/gnatsd | conf/lex.go | lexCommentStart | func lexCommentStart(lx *lexer) stateFn {
lx.ignore()
lx.emit(itemCommentStart)
return lexComment
} | go | func lexCommentStart(lx *lexer) stateFn {
lx.ignore()
lx.emit(itemCommentStart)
return lexComment
} | [
"func",
"lexCommentStart",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"lx",
".",
"ignore",
"(",
")",
"\n",
"lx",
".",
"emit",
"(",
"itemCommentStart",
")",
"\n",
"return",
"lexComment",
"\n",
"}"
] | // lexCommentStart begins the lexing of a comment. It will emit
// itemCommentStart and consume no characters, passing control to lexComment. | [
"lexCommentStart",
"begins",
"the",
"lexing",
"of",
"a",
"comment",
".",
"It",
"will",
"emit",
"itemCommentStart",
"and",
"consume",
"no",
"characters",
"passing",
"control",
"to",
"lexComment",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L1106-L1110 |
164,359 | nats-io/gnatsd | conf/lex.go | lexSkip | func lexSkip(lx *lexer, nextState stateFn) stateFn {
return func(lx *lexer) stateFn {
lx.ignore()
return nextState
}
} | go | func lexSkip(lx *lexer, nextState stateFn) stateFn {
return func(lx *lexer) stateFn {
lx.ignore()
return nextState
}
} | [
"func",
"lexSkip",
"(",
"lx",
"*",
"lexer",
",",
"nextState",
"stateFn",
")",
"stateFn",
"{",
"return",
"func",
"(",
"lx",
"*",
"lexer",
")",
"stateFn",
"{",
"lx",
".",
"ignore",
"(",
")",
"\n",
"return",
"nextState",
"\n",
"}",
"\n",
"}"
] | // lexSkip ignores all slurped input and moves on to the next state. | [
"lexSkip",
"ignores",
"all",
"slurped",
"input",
"and",
"moves",
"on",
"to",
"the",
"next",
"state",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L1126-L1131 |
164,360 | nats-io/gnatsd | conf/lex.go | isNumberSuffix | func isNumberSuffix(r rune) bool {
return r == 'k' || r == 'K' || r == 'm' || r == 'M' || r == 'g' || r == 'G'
} | go | func isNumberSuffix(r rune) bool {
return r == 'k' || r == 'K' || r == 'm' || r == 'M' || r == 'g' || r == 'G'
} | [
"func",
"isNumberSuffix",
"(",
"r",
"rune",
")",
"bool",
"{",
"return",
"r",
"==",
"'k'",
"||",
"r",
"==",
"'K'",
"||",
"r",
"==",
"'m'",
"||",
"r",
"==",
"'M'",
"||",
"r",
"==",
"'g'",
"||",
"r",
"==",
"'G'",
"\n",
"}"
] | // Tests to see if we have a number suffix | [
"Tests",
"to",
"see",
"if",
"we",
"have",
"a",
"number",
"suffix"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/conf/lex.go#L1134-L1136 |
164,361 | nats-io/gnatsd | server/leafnode.go | solicitLeafNodeRemotes | func (s *Server) solicitLeafNodeRemotes(remotes []*RemoteLeafOpts) {
for _, r := range remotes {
remote := newLeafNodeCfg(r)
s.startGoRoutine(func() { s.connectToRemoteLeafNode(remote) })
}
} | go | func (s *Server) solicitLeafNodeRemotes(remotes []*RemoteLeafOpts) {
for _, r := range remotes {
remote := newLeafNodeCfg(r)
s.startGoRoutine(func() { s.connectToRemoteLeafNode(remote) })
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"solicitLeafNodeRemotes",
"(",
"remotes",
"[",
"]",
"*",
"RemoteLeafOpts",
")",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"remotes",
"{",
"remote",
":=",
"newLeafNodeCfg",
"(",
"r",
")",
"\n",
"s",
".",
"startGoRou... | // This will spin up go routines to solicit the remote leaf node connections. | [
"This",
"will",
"spin",
"up",
"go",
"routines",
"to",
"solicit",
"the",
"remote",
"leaf",
"node",
"connections",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L59-L64 |
164,362 | nats-io/gnatsd | server/leafnode.go | validateLeafNode | func validateLeafNode(o *Options) error {
if o.LeafNode.Port == 0 {
return nil
}
if o.Gateway.Name == "" && o.Gateway.Port == 0 {
return nil
}
// If we are here we have both leaf nodes and gateways defined, make sure there
// is a system account defined.
if o.SystemAccount == "" {
return fmt.Errorf("leaf nodes and gateways (both being defined) require a system account to also be configured")
}
return nil
} | go | func validateLeafNode(o *Options) error {
if o.LeafNode.Port == 0 {
return nil
}
if o.Gateway.Name == "" && o.Gateway.Port == 0 {
return nil
}
// If we are here we have both leaf nodes and gateways defined, make sure there
// is a system account defined.
if o.SystemAccount == "" {
return fmt.Errorf("leaf nodes and gateways (both being defined) require a system account to also be configured")
}
return nil
} | [
"func",
"validateLeafNode",
"(",
"o",
"*",
"Options",
")",
"error",
"{",
"if",
"o",
".",
"LeafNode",
".",
"Port",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"o",
".",
"Gateway",
".",
"Name",
"==",
"\"",
"\"",
"&&",
"o",
".",
"Gateway... | // Ensure that leafnode is properly configured. | [
"Ensure",
"that",
"leafnode",
"is",
"properly",
"configured",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L77-L90 |
164,363 | nats-io/gnatsd | server/leafnode.go | newLeafNodeCfg | func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
cfg := &leafNodeCfg{
RemoteLeafOpts: remote,
urls: make([]*url.URL, 0, 4),
}
// Start with the one that is configured. We will add to this
// array when receiving async leafnode INFOs.
cfg.urls = append(cfg.urls, cfg.URL)
return cfg
} | go | func newLeafNodeCfg(remote *RemoteLeafOpts) *leafNodeCfg {
cfg := &leafNodeCfg{
RemoteLeafOpts: remote,
urls: make([]*url.URL, 0, 4),
}
// Start with the one that is configured. We will add to this
// array when receiving async leafnode INFOs.
cfg.urls = append(cfg.urls, cfg.URL)
return cfg
} | [
"func",
"newLeafNodeCfg",
"(",
"remote",
"*",
"RemoteLeafOpts",
")",
"*",
"leafNodeCfg",
"{",
"cfg",
":=",
"&",
"leafNodeCfg",
"{",
"RemoteLeafOpts",
":",
"remote",
",",
"urls",
":",
"make",
"(",
"[",
"]",
"*",
"url",
".",
"URL",
",",
"0",
",",
"4",
... | // Creates a leafNodeCfg object that wraps the RemoteLeafOpts. | [
"Creates",
"a",
"leafNodeCfg",
"object",
"that",
"wraps",
"the",
"RemoteLeafOpts",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L104-L113 |
164,364 | nats-io/gnatsd | server/leafnode.go | pickNextURL | func (cfg *leafNodeCfg) pickNextURL() *url.URL {
cfg.Lock()
defer cfg.Unlock()
// If the current URL is the first in the list and we have more than
// one URL, then move that one to end of the list.
if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) {
first := cfg.urls[0]
copy(cfg.urls, cfg.urls[1:])
cfg.urls[len(cfg.urls)-1] = first
}
cfg.curURL = cfg.urls[0]
return cfg.curURL
} | go | func (cfg *leafNodeCfg) pickNextURL() *url.URL {
cfg.Lock()
defer cfg.Unlock()
// If the current URL is the first in the list and we have more than
// one URL, then move that one to end of the list.
if cfg.curURL != nil && len(cfg.urls) > 1 && urlsAreEqual(cfg.curURL, cfg.urls[0]) {
first := cfg.urls[0]
copy(cfg.urls, cfg.urls[1:])
cfg.urls[len(cfg.urls)-1] = first
}
cfg.curURL = cfg.urls[0]
return cfg.curURL
} | [
"func",
"(",
"cfg",
"*",
"leafNodeCfg",
")",
"pickNextURL",
"(",
")",
"*",
"url",
".",
"URL",
"{",
"cfg",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cfg",
".",
"Unlock",
"(",
")",
"\n",
"// If the current URL is the first in the list and we have more than",
"// on... | // Will pick an URL from the list of available URLs. | [
"Will",
"pick",
"an",
"URL",
"from",
"the",
"list",
"of",
"available",
"URLs",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L116-L128 |
164,365 | nats-io/gnatsd | server/leafnode.go | getCurrentURL | func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
cfg.RLock()
defer cfg.RUnlock()
return cfg.curURL
} | go | func (cfg *leafNodeCfg) getCurrentURL() *url.URL {
cfg.RLock()
defer cfg.RUnlock()
return cfg.curURL
} | [
"func",
"(",
"cfg",
"*",
"leafNodeCfg",
")",
"getCurrentURL",
"(",
")",
"*",
"url",
".",
"URL",
"{",
"cfg",
".",
"RLock",
"(",
")",
"\n",
"defer",
"cfg",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"cfg",
".",
"curURL",
"\n",
"}"
] | // Returns the current URL | [
"Returns",
"the",
"current",
"URL"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L131-L135 |
164,366 | nats-io/gnatsd | server/leafnode.go | copyLeafNodeInfo | func (s *Server) copyLeafNodeInfo() *Info {
clone := s.leafNodeInfo
// Copy the array of urls.
if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
}
return &clone
} | go | func (s *Server) copyLeafNodeInfo() *Info {
clone := s.leafNodeInfo
// Copy the array of urls.
if len(s.leafNodeInfo.LeafNodeURLs) > 0 {
clone.LeafNodeURLs = append([]string(nil), s.leafNodeInfo.LeafNodeURLs...)
}
return &clone
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"copyLeafNodeInfo",
"(",
")",
"*",
"Info",
"{",
"clone",
":=",
"s",
".",
"leafNodeInfo",
"\n",
"// Copy the array of urls.",
"if",
"len",
"(",
"s",
".",
"leafNodeInfo",
".",
"LeafNodeURLs",
")",
">",
"0",
"{",
"clone... | // Makes a deep copy of the LeafNode Info structure.
// The server lock is held on entry. | [
"Makes",
"a",
"deep",
"copy",
"of",
"the",
"LeafNode",
"Info",
"structure",
".",
"The",
"server",
"lock",
"is",
"held",
"on",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L348-L355 |
164,367 | nats-io/gnatsd | server/leafnode.go | addLeafNodeURL | func (s *Server) addLeafNodeURL(urlStr string) bool {
// Make sure we already don't have it.
for _, url := range s.leafNodeInfo.LeafNodeURLs {
if url == urlStr {
return false
}
}
s.leafNodeInfo.LeafNodeURLs = append(s.leafNodeInfo.LeafNodeURLs, urlStr)
s.generateLeafNodeInfoJSON()
return true
} | go | func (s *Server) addLeafNodeURL(urlStr string) bool {
// Make sure we already don't have it.
for _, url := range s.leafNodeInfo.LeafNodeURLs {
if url == urlStr {
return false
}
}
s.leafNodeInfo.LeafNodeURLs = append(s.leafNodeInfo.LeafNodeURLs, urlStr)
s.generateLeafNodeInfoJSON()
return true
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"addLeafNodeURL",
"(",
"urlStr",
"string",
")",
"bool",
"{",
"// Make sure we already don't have it.",
"for",
"_",
",",
"url",
":=",
"range",
"s",
".",
"leafNodeInfo",
".",
"LeafNodeURLs",
"{",
"if",
"url",
"==",
"urlStr... | // Adds a LeafNode URL that we get when a route connects to the Info structure.
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
// Returns a boolean indicating if the URL was added or not.
// Server lock is held on entry | [
"Adds",
"a",
"LeafNode",
"URL",
"that",
"we",
"get",
"when",
"a",
"route",
"connects",
"to",
"the",
"Info",
"structure",
".",
"Regenerates",
"the",
"JSON",
"byte",
"array",
"so",
"that",
"it",
"can",
"be",
"sent",
"to",
"LeafNode",
"connections",
".",
"R... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L361-L371 |
164,368 | nats-io/gnatsd | server/leafnode.go | removeLeafNodeURL | func (s *Server) removeLeafNodeURL(urlStr string) bool {
// Don't need to do this if we are removing the route connection because
// we are shuting down...
if s.shutdown {
return false
}
removed := false
urls := s.leafNodeInfo.LeafNodeURLs
for i, url := range urls {
if url == urlStr {
// If not last, move last into the position we remove.
last := len(urls) - 1
if i != last {
urls[i] = urls[last]
}
s.leafNodeInfo.LeafNodeURLs = urls[0:last]
removed = true
break
}
}
if removed {
s.generateLeafNodeInfoJSON()
}
return removed
} | go | func (s *Server) removeLeafNodeURL(urlStr string) bool {
// Don't need to do this if we are removing the route connection because
// we are shuting down...
if s.shutdown {
return false
}
removed := false
urls := s.leafNodeInfo.LeafNodeURLs
for i, url := range urls {
if url == urlStr {
// If not last, move last into the position we remove.
last := len(urls) - 1
if i != last {
urls[i] = urls[last]
}
s.leafNodeInfo.LeafNodeURLs = urls[0:last]
removed = true
break
}
}
if removed {
s.generateLeafNodeInfoJSON()
}
return removed
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"removeLeafNodeURL",
"(",
"urlStr",
"string",
")",
"bool",
"{",
"// Don't need to do this if we are removing the route connection because",
"// we are shuting down...",
"if",
"s",
".",
"shutdown",
"{",
"return",
"false",
"\n",
"}",
... | // Removes a LeafNode URL of the route that is disconnecting from the Info structure.
// Regenerates the JSON byte array so that it can be sent to LeafNode connections.
// Returns a boolean indicating if the URL was removed or not.
// Server lock is held on entry. | [
"Removes",
"a",
"LeafNode",
"URL",
"of",
"the",
"route",
"that",
"is",
"disconnecting",
"from",
"the",
"Info",
"structure",
".",
"Regenerates",
"the",
"JSON",
"byte",
"array",
"so",
"that",
"it",
"can",
"be",
"sent",
"to",
"LeafNode",
"connections",
".",
"... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L377-L401 |
164,369 | nats-io/gnatsd | server/leafnode.go | sendAsyncLeafNodeInfo | func (s *Server) sendAsyncLeafNodeInfo() {
for _, c := range s.leafs {
c.mu.Lock()
c.sendInfo(s.leafNodeInfoJSON)
c.mu.Unlock()
}
} | go | func (s *Server) sendAsyncLeafNodeInfo() {
for _, c := range s.leafs {
c.mu.Lock()
c.sendInfo(s.leafNodeInfoJSON)
c.mu.Unlock()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"sendAsyncLeafNodeInfo",
"(",
")",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"s",
".",
"leafs",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"sendInfo",
"(",
"s",
".",
"leafNodeInfoJSON",
")",
... | // Sends an async INFO protocol so that the connected servers can update
// their list of LeafNode urls. | [
"Sends",
"an",
"async",
"INFO",
"protocol",
"so",
"that",
"the",
"connected",
"servers",
"can",
"update",
"their",
"list",
"of",
"LeafNode",
"urls",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L411-L417 |
164,370 | nats-io/gnatsd | server/leafnode.go | updateLeafNodeURLs | func (c *client) updateLeafNodeURLs(info *Info) {
cfg := c.leaf.remote
cfg.Lock()
defer cfg.Unlock()
cfg.urls = make([]*url.URL, 0, 1+len(info.LeafNodeURLs))
// Add the ones we receive in the protocol
for _, surl := range info.LeafNodeURLs {
url, err := url.Parse("nats-leaf://" + surl)
if err != nil {
c.Errorf("Error parsing url %q: %v", surl, err)
continue
}
// Do not add if it's the same than the one that
// we have configured.
if urlsAreEqual(url, cfg.URL) {
continue
}
cfg.urls = append(cfg.urls, url)
}
// Add the configured one
cfg.urls = append(cfg.urls, cfg.URL)
} | go | func (c *client) updateLeafNodeURLs(info *Info) {
cfg := c.leaf.remote
cfg.Lock()
defer cfg.Unlock()
cfg.urls = make([]*url.URL, 0, 1+len(info.LeafNodeURLs))
// Add the ones we receive in the protocol
for _, surl := range info.LeafNodeURLs {
url, err := url.Parse("nats-leaf://" + surl)
if err != nil {
c.Errorf("Error parsing url %q: %v", surl, err)
continue
}
// Do not add if it's the same than the one that
// we have configured.
if urlsAreEqual(url, cfg.URL) {
continue
}
cfg.urls = append(cfg.urls, url)
}
// Add the configured one
cfg.urls = append(cfg.urls, cfg.URL)
} | [
"func",
"(",
"c",
"*",
"client",
")",
"updateLeafNodeURLs",
"(",
"info",
"*",
"Info",
")",
"{",
"cfg",
":=",
"c",
".",
"leaf",
".",
"remote",
"\n",
"cfg",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cfg",
".",
"Unlock",
"(",
")",
"\n\n",
"cfg",
".",
... | // When getting a leaf node INFO protocol, use the provided
// array of urls to update the list of possible endpoints. | [
"When",
"getting",
"a",
"leaf",
"node",
"INFO",
"protocol",
"use",
"the",
"provided",
"array",
"of",
"urls",
"to",
"update",
"the",
"list",
"of",
"possible",
"endpoints",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L648-L670 |
164,371 | nats-io/gnatsd | server/leafnode.go | setLeafNodeInfoHostPortAndIP | func (s *Server) setLeafNodeInfoHostPortAndIP() error {
opts := s.getOpts()
if opts.LeafNode.Advertise != _EMPTY_ {
advHost, advPort, err := parseHostPort(opts.LeafNode.Advertise, opts.LeafNode.Port)
if err != nil {
return err
}
s.leafNodeInfo.Host = advHost
s.leafNodeInfo.Port = advPort
} else {
s.leafNodeInfo.Host = opts.LeafNode.Host
s.leafNodeInfo.Port = opts.LeafNode.Port
// If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
// This will return at most 1 IP.
hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
if err != nil {
return err
}
if hostIsIPAny {
if len(ips) == 0 {
s.Errorf("Could not find any non-local IP for leafnode's listen specification %q",
s.leafNodeInfo.Host)
} else {
// Take the first from the list...
s.leafNodeInfo.Host = ips[0]
}
}
}
// Use just host:port for the IP
s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port))
if opts.LeafNode.Advertise != _EMPTY_ {
s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
}
return nil
} | go | func (s *Server) setLeafNodeInfoHostPortAndIP() error {
opts := s.getOpts()
if opts.LeafNode.Advertise != _EMPTY_ {
advHost, advPort, err := parseHostPort(opts.LeafNode.Advertise, opts.LeafNode.Port)
if err != nil {
return err
}
s.leafNodeInfo.Host = advHost
s.leafNodeInfo.Port = advPort
} else {
s.leafNodeInfo.Host = opts.LeafNode.Host
s.leafNodeInfo.Port = opts.LeafNode.Port
// If the host is "0.0.0.0" or "::" we need to resolve to a public IP.
// This will return at most 1 IP.
hostIsIPAny, ips, err := s.getNonLocalIPsIfHostIsIPAny(s.leafNodeInfo.Host, false)
if err != nil {
return err
}
if hostIsIPAny {
if len(ips) == 0 {
s.Errorf("Could not find any non-local IP for leafnode's listen specification %q",
s.leafNodeInfo.Host)
} else {
// Take the first from the list...
s.leafNodeInfo.Host = ips[0]
}
}
}
// Use just host:port for the IP
s.leafNodeInfo.IP = net.JoinHostPort(s.leafNodeInfo.Host, strconv.Itoa(s.leafNodeInfo.Port))
if opts.LeafNode.Advertise != _EMPTY_ {
s.Noticef("Advertise address for leafnode is set to %s", s.leafNodeInfo.IP)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"setLeafNodeInfoHostPortAndIP",
"(",
")",
"error",
"{",
"opts",
":=",
"s",
".",
"getOpts",
"(",
")",
"\n",
"if",
"opts",
".",
"LeafNode",
".",
"Advertise",
"!=",
"_EMPTY_",
"{",
"advHost",
",",
"advPort",
",",
"err... | // Similar to setInfoHostPortAndGenerateJSON, but for leafNodeInfo. | [
"Similar",
"to",
"setInfoHostPortAndGenerateJSON",
"but",
"for",
"leafNodeInfo",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L673-L707 |
164,372 | nats-io/gnatsd | server/leafnode.go | processLeafNodeConnect | func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) error {
// Way to detect clients that incorrectly connect to the route listen
// port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
if lang != "" {
c.sendErrAndErr(ErrClientConnectedToLeafNodePort.Error())
c.closeConnection(WrongPort)
return ErrClientConnectedToLeafNodePort
}
// Unmarshal as a leaf node connect protocol
proto := &leafConnectInfo{}
if err := json.Unmarshal(arg, proto); err != nil {
return err
}
// Reject if this has Gateway which means that it would be from a gateway
// connection that incorrectly connects to the leafnode port.
if proto.Gateway != "" {
errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
c.Errorf(errTxt)
c.sendErr(errTxt)
c.closeConnection(WrongGateway)
return ErrWrongGateway
}
// Leaf Nodes do not do echo or verbose or pedantic.
c.opts.Verbose = false
c.opts.Echo = false
c.opts.Pedantic = false
// Create and initialize the smap since we know our bound account now.
s.initLeafNodeSmap(c)
// We are good to go, send over all the bound account subscriptions.
s.startGoRoutine(func() {
c.sendAllAccountSubs()
s.grWG.Done()
})
// Add in the leafnode here since we passed through auth at this point.
s.addLeafNodeConnection(c)
// Announce the account connect event for a leaf node.
// This will no-op as needed.
s.sendLeafNodeConnect(c.acc)
return nil
} | go | func (c *client) processLeafNodeConnect(s *Server, arg []byte, lang string) error {
// Way to detect clients that incorrectly connect to the route listen
// port. Client provided "lang" in the CONNECT protocol while LEAFNODEs don't.
if lang != "" {
c.sendErrAndErr(ErrClientConnectedToLeafNodePort.Error())
c.closeConnection(WrongPort)
return ErrClientConnectedToLeafNodePort
}
// Unmarshal as a leaf node connect protocol
proto := &leafConnectInfo{}
if err := json.Unmarshal(arg, proto); err != nil {
return err
}
// Reject if this has Gateway which means that it would be from a gateway
// connection that incorrectly connects to the leafnode port.
if proto.Gateway != "" {
errTxt := fmt.Sprintf("Rejecting connection from gateway %q on the leafnode port", proto.Gateway)
c.Errorf(errTxt)
c.sendErr(errTxt)
c.closeConnection(WrongGateway)
return ErrWrongGateway
}
// Leaf Nodes do not do echo or verbose or pedantic.
c.opts.Verbose = false
c.opts.Echo = false
c.opts.Pedantic = false
// Create and initialize the smap since we know our bound account now.
s.initLeafNodeSmap(c)
// We are good to go, send over all the bound account subscriptions.
s.startGoRoutine(func() {
c.sendAllAccountSubs()
s.grWG.Done()
})
// Add in the leafnode here since we passed through auth at this point.
s.addLeafNodeConnection(c)
// Announce the account connect event for a leaf node.
// This will no-op as needed.
s.sendLeafNodeConnect(c.acc)
return nil
} | [
"func",
"(",
"c",
"*",
"client",
")",
"processLeafNodeConnect",
"(",
"s",
"*",
"Server",
",",
"arg",
"[",
"]",
"byte",
",",
"lang",
"string",
")",
"error",
"{",
"// Way to detect clients that incorrectly connect to the route listen",
"// port. Client provided \"lang\" i... | // processLeafNodeConnect will process the inbound connect args.
// Once we are here we are bound to an account, so can send any interest that
// we would have to the other side. | [
"processLeafNodeConnect",
"will",
"process",
"the",
"inbound",
"connect",
"args",
".",
"Once",
"we",
"are",
"here",
"we",
"are",
"bound",
"to",
"an",
"account",
"so",
"can",
"send",
"any",
"interest",
"that",
"we",
"would",
"have",
"to",
"the",
"other",
"s... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L743-L790 |
164,373 | nats-io/gnatsd | server/leafnode.go | initLeafNodeSmap | func (s *Server) initLeafNodeSmap(c *client) {
acc := c.acc
if acc == nil {
c.Debugf("Leaf node does not have an account bound")
return
}
// Collect all account subs here.
_subs := [32]*subscription{}
subs := _subs[:0]
ims := []string{}
acc.mu.RLock()
accName := acc.Name
acc.sl.All(&subs)
// Since leaf nodes only send on interest, if the bound
// account has import services we need to send those over.
for isubj := range acc.imports.services {
ims = append(ims, isubj)
}
acc.mu.RUnlock()
// Now check for gateway interest. Leafnodes will put this into
// the proper mode to propagate, but they are not held in the account.
gwsa := [16]*client{}
gws := gwsa[:0]
s.getOutboundGatewayConnections(&gws)
for _, cgw := range gws {
cgw.mu.Lock()
gw := cgw.gw
cgw.mu.Unlock()
if gw != nil {
if ei, _ := gw.outsim.Load(accName); ei != nil {
if e := ei.(*outsie); e != nil && e.sl != nil {
e.sl.All(&subs)
}
}
}
}
// Now walk the results and add them to our smap
c.mu.Lock()
for _, sub := range subs {
// We ignore ourselves here.
if c != sub.client {
c.leaf.smap[keyFromSub(sub)]++
}
}
// FIXME(dlc) - We need to update appropriately on an account claims update.
for _, isubj := range ims {
c.leaf.smap[isubj]++
}
c.mu.Unlock()
} | go | func (s *Server) initLeafNodeSmap(c *client) {
acc := c.acc
if acc == nil {
c.Debugf("Leaf node does not have an account bound")
return
}
// Collect all account subs here.
_subs := [32]*subscription{}
subs := _subs[:0]
ims := []string{}
acc.mu.RLock()
accName := acc.Name
acc.sl.All(&subs)
// Since leaf nodes only send on interest, if the bound
// account has import services we need to send those over.
for isubj := range acc.imports.services {
ims = append(ims, isubj)
}
acc.mu.RUnlock()
// Now check for gateway interest. Leafnodes will put this into
// the proper mode to propagate, but they are not held in the account.
gwsa := [16]*client{}
gws := gwsa[:0]
s.getOutboundGatewayConnections(&gws)
for _, cgw := range gws {
cgw.mu.Lock()
gw := cgw.gw
cgw.mu.Unlock()
if gw != nil {
if ei, _ := gw.outsim.Load(accName); ei != nil {
if e := ei.(*outsie); e != nil && e.sl != nil {
e.sl.All(&subs)
}
}
}
}
// Now walk the results and add them to our smap
c.mu.Lock()
for _, sub := range subs {
// We ignore ourselves here.
if c != sub.client {
c.leaf.smap[keyFromSub(sub)]++
}
}
// FIXME(dlc) - We need to update appropriately on an account claims update.
for _, isubj := range ims {
c.leaf.smap[isubj]++
}
c.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"initLeafNodeSmap",
"(",
"c",
"*",
"client",
")",
"{",
"acc",
":=",
"c",
".",
"acc",
"\n",
"if",
"acc",
"==",
"nil",
"{",
"c",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Colle... | // Snapshot the current subscriptions from the sublist into our smap which
// we will keep updated from now on. | [
"Snapshot",
"the",
"current",
"subscriptions",
"from",
"the",
"sublist",
"into",
"our",
"smap",
"which",
"we",
"will",
"keep",
"updated",
"from",
"now",
"on",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L794-L845 |
164,374 | nats-io/gnatsd | server/leafnode.go | updateInterestForAccountOnGateway | func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
acc, err := s.LookupAccount(accName)
if acc == nil || err != nil {
s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
return
}
s.updateLeafNodes(acc, sub, delta)
} | go | func (s *Server) updateInterestForAccountOnGateway(accName string, sub *subscription, delta int32) {
acc, err := s.LookupAccount(accName)
if acc == nil || err != nil {
s.Debugf("No or bad account for %q, failed to update interest from gateway", accName)
return
}
s.updateLeafNodes(acc, sub, delta)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"updateInterestForAccountOnGateway",
"(",
"accName",
"string",
",",
"sub",
"*",
"subscription",
",",
"delta",
"int32",
")",
"{",
"acc",
",",
"err",
":=",
"s",
".",
"LookupAccount",
"(",
"accName",
")",
"\n",
"if",
"a... | // updateInterestForAccountOnGateway called from gateway code when processing RS+ and RS-. | [
"updateInterestForAccountOnGateway",
"called",
"from",
"gateway",
"code",
"when",
"processing",
"RS",
"+",
"and",
"RS",
"-",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L848-L855 |
164,375 | nats-io/gnatsd | server/leafnode.go | updateLeafNodes | func (s *Server) updateLeafNodes(acc *Account, sub *subscription, delta int32) {
if acc == nil || sub == nil {
return
}
_l := [256]*client{}
leafs := _l[:0]
// Grab all leaf nodes. Ignore leafnode if sub's client is a leafnode and matches.
acc.mu.RLock()
for _, ln := range acc.clients {
if ln.kind == LEAF && ln != sub.client {
leafs = append(leafs, ln)
}
}
acc.mu.RUnlock()
for _, ln := range leafs {
ln.updateSmap(sub, delta)
}
} | go | func (s *Server) updateLeafNodes(acc *Account, sub *subscription, delta int32) {
if acc == nil || sub == nil {
return
}
_l := [256]*client{}
leafs := _l[:0]
// Grab all leaf nodes. Ignore leafnode if sub's client is a leafnode and matches.
acc.mu.RLock()
for _, ln := range acc.clients {
if ln.kind == LEAF && ln != sub.client {
leafs = append(leafs, ln)
}
}
acc.mu.RUnlock()
for _, ln := range leafs {
ln.updateSmap(sub, delta)
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"updateLeafNodes",
"(",
"acc",
"*",
"Account",
",",
"sub",
"*",
"subscription",
",",
"delta",
"int32",
")",
"{",
"if",
"acc",
"==",
"nil",
"||",
"sub",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"_l",
":=",... | // updateLeafNodes will make sure to update the smap for the subscription. Will
// also forward to all leaf nodes as needed. | [
"updateLeafNodes",
"will",
"make",
"sure",
"to",
"update",
"the",
"smap",
"for",
"the",
"subscription",
".",
"Will",
"also",
"forward",
"to",
"all",
"leaf",
"nodes",
"as",
"needed",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L859-L879 |
164,376 | nats-io/gnatsd | server/leafnode.go | updateSmap | func (c *client) updateSmap(sub *subscription, delta int32) {
key := keyFromSub(sub)
c.mu.Lock()
n := c.leaf.smap[key]
// We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
update := sub.queue != nil || n == 0 || n+delta <= 0
n += delta
if n > 0 {
c.leaf.smap[key] = n
} else {
delete(c.leaf.smap, key)
}
if update {
c.sendLeafNodeSubUpdate(key, n)
}
c.mu.Unlock()
} | go | func (c *client) updateSmap(sub *subscription, delta int32) {
key := keyFromSub(sub)
c.mu.Lock()
n := c.leaf.smap[key]
// We will update if its a queue, if count is zero (or negative), or we were 0 and are N > 0.
update := sub.queue != nil || n == 0 || n+delta <= 0
n += delta
if n > 0 {
c.leaf.smap[key] = n
} else {
delete(c.leaf.smap, key)
}
if update {
c.sendLeafNodeSubUpdate(key, n)
}
c.mu.Unlock()
} | [
"func",
"(",
"c",
"*",
"client",
")",
"updateSmap",
"(",
"sub",
"*",
"subscription",
",",
"delta",
"int32",
")",
"{",
"key",
":=",
"keyFromSub",
"(",
"sub",
")",
"\n\n",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"n",
":=",
"c",
".",
"leaf",
... | // This will make an update to our internal smap and determine if we should send out
// and interest update to the remote side. | [
"This",
"will",
"make",
"an",
"update",
"to",
"our",
"internal",
"smap",
"and",
"determine",
"if",
"we",
"should",
"send",
"out",
"and",
"interest",
"update",
"to",
"the",
"remote",
"side",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L883-L900 |
164,377 | nats-io/gnatsd | server/leafnode.go | sendLeafNodeSubUpdate | func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
_b := [64]byte{}
b := bytes.NewBuffer(_b[:0])
c.writeLeafSub(b, key, n)
c.sendProto(b.Bytes(), false)
} | go | func (c *client) sendLeafNodeSubUpdate(key string, n int32) {
_b := [64]byte{}
b := bytes.NewBuffer(_b[:0])
c.writeLeafSub(b, key, n)
c.sendProto(b.Bytes(), false)
} | [
"func",
"(",
"c",
"*",
"client",
")",
"sendLeafNodeSubUpdate",
"(",
"key",
"string",
",",
"n",
"int32",
")",
"{",
"_b",
":=",
"[",
"64",
"]",
"byte",
"{",
"}",
"\n",
"b",
":=",
"bytes",
".",
"NewBuffer",
"(",
"_b",
"[",
":",
"0",
"]",
")",
"\n"... | // Send the subscription interest change to the other side.
// Lock should be held. | [
"Send",
"the",
"subscription",
"interest",
"change",
"to",
"the",
"other",
"side",
".",
"Lock",
"should",
"be",
"held",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L904-L909 |
164,378 | nats-io/gnatsd | server/leafnode.go | keyFromSub | func keyFromSub(sub *subscription) string {
var _rkey [1024]byte
var key []byte
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...)
} else {
key = sub.subject
}
return string(key)
} | go | func keyFromSub(sub *subscription) string {
var _rkey [1024]byte
var key []byte
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...)
} else {
key = sub.subject
}
return string(key)
} | [
"func",
"keyFromSub",
"(",
"sub",
"*",
"subscription",
")",
"string",
"{",
"var",
"_rkey",
"[",
"1024",
"]",
"byte",
"\n",
"var",
"key",
"[",
"]",
"byte",
"\n\n",
"if",
"sub",
".",
"queue",
"!=",
"nil",
"{",
"// Just make the key subject spc group, e.g. 'foo... | // Helper function to build the key. | [
"Helper",
"function",
"to",
"build",
"the",
"key",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L912-L926 |
164,379 | nats-io/gnatsd | server/leafnode.go | sendAllAccountSubs | func (c *client) sendAllAccountSubs() {
// Hold all at once for now.
var b bytes.Buffer
c.mu.Lock()
for key, n := range c.leaf.smap {
c.writeLeafSub(&b, key, n)
}
// We will make sure we don't overflow here due to an max_pending.
chunks := protoChunks(b.Bytes(), MAX_PAYLOAD_SIZE)
for _, chunk := range chunks {
c.queueOutbound(chunk)
c.flushOutbound()
}
c.mu.Unlock()
} | go | func (c *client) sendAllAccountSubs() {
// Hold all at once for now.
var b bytes.Buffer
c.mu.Lock()
for key, n := range c.leaf.smap {
c.writeLeafSub(&b, key, n)
}
// We will make sure we don't overflow here due to an max_pending.
chunks := protoChunks(b.Bytes(), MAX_PAYLOAD_SIZE)
for _, chunk := range chunks {
c.queueOutbound(chunk)
c.flushOutbound()
}
c.mu.Unlock()
} | [
"func",
"(",
"c",
"*",
"client",
")",
"sendAllAccountSubs",
"(",
")",
"{",
"// Hold all at once for now.",
"var",
"b",
"bytes",
".",
"Buffer",
"\n\n",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"for",
"key",
",",
"n",
":=",
"range",
"c",
".",
"leaf... | // Send all subscriptions for this account that include local
// and all subscriptions besides our own. | [
"Send",
"all",
"subscriptions",
"for",
"this",
"account",
"that",
"include",
"local",
"and",
"all",
"subscriptions",
"besides",
"our",
"own",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L930-L946 |
164,380 | nats-io/gnatsd | server/leafnode.go | processLeafSub | func (c *client) processLeafSub(argo []byte) (err error) {
c.traceInOp("LS+", argo)
// Indicate activity.
c.in.subs++
srv := c.srv
if srv == nil {
return nil
}
// Copy so we do not reference a potentially large buffer
arg := make([]byte, len(argo))
copy(arg, argo)
args := splitArg(arg)
sub := &subscription{client: c}
switch len(args) {
case 1:
sub.queue = nil
case 3:
sub.queue = args[1]
sub.qw = int32(parseSize(args[2]))
default:
return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
}
sub.subject = args[0]
c.mu.Lock()
if c.nc == nil {
c.mu.Unlock()
return nil
}
// Check permissions if applicable.
if !c.canExport(string(sub.subject)) {
c.mu.Unlock()
c.Debugf("Can not export %q, ignoring remote subscription request", sub.subject)
return nil
}
// Check if we have a maximum on the number of subscriptions.
if c.subsAtLimit() {
c.mu.Unlock()
c.maxSubsExceeded()
return nil
}
// Like Routes, we store local subs by account and subject and optionally queue name.
// If we have a queue it will have a trailing weight which we do not want.
if sub.queue != nil {
sub.sid = arg[:len(arg)-len(args[2])-1]
} else {
sub.sid = arg
}
acc := c.acc
key := string(sub.sid)
osub := c.subs[key]
updateGWs := false
if osub == nil {
c.subs[key] = sub
// Now place into the account sl.
if err = acc.sl.Insert(sub); err != nil {
delete(c.subs, key)
c.mu.Unlock()
c.Errorf("Could not insert subscription: %v", err)
c.sendErr("Invalid Subscription")
return nil
}
updateGWs = srv.gateway.enabled
} else if sub.queue != nil {
// For a queue we need to update the weight.
atomic.StoreInt32(&osub.qw, sub.qw)
acc.sl.UpdateRemoteQSub(osub)
}
c.mu.Unlock()
// Treat leaf node subscriptions similar to a client subscription, meaning we
// send them to both routes and gateways and other leaf nodes. We also do
// the shadow subscriptions.
if err := c.addShadowSubscriptions(acc, sub); err != nil {
c.Errorf(err.Error())
}
// If we are routing add to the route map for the associated account.
srv.updateRouteSubscriptionMap(acc, sub, 1)
if updateGWs {
srv.gatewayUpdateSubInterest(acc.Name, sub, 1)
}
// Now check on leafnode updates for other leaf nodes.
srv.updateLeafNodes(acc, sub, 1)
return nil
} | go | func (c *client) processLeafSub(argo []byte) (err error) {
c.traceInOp("LS+", argo)
// Indicate activity.
c.in.subs++
srv := c.srv
if srv == nil {
return nil
}
// Copy so we do not reference a potentially large buffer
arg := make([]byte, len(argo))
copy(arg, argo)
args := splitArg(arg)
sub := &subscription{client: c}
switch len(args) {
case 1:
sub.queue = nil
case 3:
sub.queue = args[1]
sub.qw = int32(parseSize(args[2]))
default:
return fmt.Errorf("processLeafSub Parse Error: '%s'", arg)
}
sub.subject = args[0]
c.mu.Lock()
if c.nc == nil {
c.mu.Unlock()
return nil
}
// Check permissions if applicable.
if !c.canExport(string(sub.subject)) {
c.mu.Unlock()
c.Debugf("Can not export %q, ignoring remote subscription request", sub.subject)
return nil
}
// Check if we have a maximum on the number of subscriptions.
if c.subsAtLimit() {
c.mu.Unlock()
c.maxSubsExceeded()
return nil
}
// Like Routes, we store local subs by account and subject and optionally queue name.
// If we have a queue it will have a trailing weight which we do not want.
if sub.queue != nil {
sub.sid = arg[:len(arg)-len(args[2])-1]
} else {
sub.sid = arg
}
acc := c.acc
key := string(sub.sid)
osub := c.subs[key]
updateGWs := false
if osub == nil {
c.subs[key] = sub
// Now place into the account sl.
if err = acc.sl.Insert(sub); err != nil {
delete(c.subs, key)
c.mu.Unlock()
c.Errorf("Could not insert subscription: %v", err)
c.sendErr("Invalid Subscription")
return nil
}
updateGWs = srv.gateway.enabled
} else if sub.queue != nil {
// For a queue we need to update the weight.
atomic.StoreInt32(&osub.qw, sub.qw)
acc.sl.UpdateRemoteQSub(osub)
}
c.mu.Unlock()
// Treat leaf node subscriptions similar to a client subscription, meaning we
// send them to both routes and gateways and other leaf nodes. We also do
// the shadow subscriptions.
if err := c.addShadowSubscriptions(acc, sub); err != nil {
c.Errorf(err.Error())
}
// If we are routing add to the route map for the associated account.
srv.updateRouteSubscriptionMap(acc, sub, 1)
if updateGWs {
srv.gatewayUpdateSubInterest(acc.Name, sub, 1)
}
// Now check on leafnode updates for other leaf nodes.
srv.updateLeafNodes(acc, sub, 1)
return nil
} | [
"func",
"(",
"c",
"*",
"client",
")",
"processLeafSub",
"(",
"argo",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"c",
".",
"traceInOp",
"(",
"\"",
"\"",
",",
"argo",
")",
"\n\n",
"// Indicate activity.",
"c",
".",
"in",
".",
"subs",
"++",... | // processLeafSub will process an inbound sub request for the remote leaf node. | [
"processLeafSub",
"will",
"process",
"an",
"inbound",
"sub",
"request",
"for",
"the",
"remote",
"leaf",
"node",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L981-L1075 |
164,381 | nats-io/gnatsd | server/leafnode.go | processLeafUnsub | func (c *client) processLeafUnsub(arg []byte) error {
c.traceInOp("LS-", arg)
// Indicate any activity, so pub and sub or unsubs.
c.in.subs++
acc := c.acc
srv := c.srv
c.mu.Lock()
if c.nc == nil {
c.mu.Unlock()
return nil
}
updateGWs := false
// We store local subs by account and subject and optionally queue name.
// LS- will have the arg exactly as the key.
sub, ok := c.subs[string(arg)]
c.mu.Unlock()
if ok {
c.unsubscribe(acc, sub, true)
updateGWs = srv.gateway.enabled
}
// If we are routing subtract from the route map for the associated account.
srv.updateRouteSubscriptionMap(acc, sub, -1)
// Gateways
if updateGWs {
srv.gatewayUpdateSubInterest(acc.Name, sub, -1)
}
// Now check on leafnode updates for other leaf nodes.
srv.updateLeafNodes(acc, sub, -1)
return nil
} | go | func (c *client) processLeafUnsub(arg []byte) error {
c.traceInOp("LS-", arg)
// Indicate any activity, so pub and sub or unsubs.
c.in.subs++
acc := c.acc
srv := c.srv
c.mu.Lock()
if c.nc == nil {
c.mu.Unlock()
return nil
}
updateGWs := false
// We store local subs by account and subject and optionally queue name.
// LS- will have the arg exactly as the key.
sub, ok := c.subs[string(arg)]
c.mu.Unlock()
if ok {
c.unsubscribe(acc, sub, true)
updateGWs = srv.gateway.enabled
}
// If we are routing subtract from the route map for the associated account.
srv.updateRouteSubscriptionMap(acc, sub, -1)
// Gateways
if updateGWs {
srv.gatewayUpdateSubInterest(acc.Name, sub, -1)
}
// Now check on leafnode updates for other leaf nodes.
srv.updateLeafNodes(acc, sub, -1)
return nil
} | [
"func",
"(",
"c",
"*",
"client",
")",
"processLeafUnsub",
"(",
"arg",
"[",
"]",
"byte",
")",
"error",
"{",
"c",
".",
"traceInOp",
"(",
"\"",
"\"",
",",
"arg",
")",
"\n\n",
"// Indicate any activity, so pub and sub or unsubs.",
"c",
".",
"in",
".",
"subs",
... | // processLeafUnsub will process an inbound unsub request for the remote leaf node. | [
"processLeafUnsub",
"will",
"process",
"an",
"inbound",
"unsub",
"request",
"for",
"the",
"remote",
"leaf",
"node",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L1078-L1113 |
164,382 | nats-io/gnatsd | server/leafnode.go | processInboundLeafMsg | func (c *client) processInboundLeafMsg(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)
}
// Check pub permissions
if c.perms != nil && (c.perms.pub.allow != nil || c.perms.pub.deny != nil) && !c.pubAllowed(string(c.pa.subject)) {
c.pubPermissionViolation(c.pa.subject)
return
}
srv := c.srv
acc := c.acc
// Mostly under testing scenarios.
if srv == nil || acc == nil {
return
}
// Match the subscriptions. We will use our own L1 map if
// it's still valid, avoiding contention on the shared sublist.
var r *SublistResult
var ok bool
genid := atomic.LoadUint64(&c.acc.sl.genid)
if genid == c.in.genid && c.in.results != nil {
r, ok = c.in.results[string(c.pa.subject)]
} else {
// Reset our L1 completely.
c.in.results = make(map[string]*SublistResult)
c.in.genid = genid
}
// Go back to the sublist data structure.
if !ok {
r = c.acc.sl.Match(string(c.pa.subject))
c.in.results[string(c.pa.subject)] = r
// Prune the results cache. Keeps us from unbounded growth. Random delete.
if len(c.in.results) > maxResultCacheSize {
n := 0
for subject := range c.in.results {
delete(c.in.results, subject)
if n++; n > pruneSize {
break
}
}
}
}
// Check to see if we need to map/route to another account.
if acc.imports.services != nil {
c.checkForImportServices(acc, msg)
}
// Collect queue names if needed.
var qnames [][]byte
// Check for no interest, short circuit if so.
// This is the fanout scale.
if len(r.psubs)+len(r.qsubs) > 0 {
flag := pmrNoFlag
// If we have queue subs in this cluster, then if we run in gateway
// mode and the remote gateways have queue subs, then we need to
// collect the queue groups this message was sent to so that we
// exclude them when sending to gateways.
if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
flag = pmrCollectQueueNames
}
qnames = c.processMsgResults(acc, r, msg, c.pa.subject, c.pa.reply, flag)
}
// Now deal with gateways
if c.srv.gateway.enabled {
c.sendMsgToGateways(c.acc, msg, c.pa.subject, c.pa.reply, qnames)
}
} | go | func (c *client) processInboundLeafMsg(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)
}
// Check pub permissions
if c.perms != nil && (c.perms.pub.allow != nil || c.perms.pub.deny != nil) && !c.pubAllowed(string(c.pa.subject)) {
c.pubPermissionViolation(c.pa.subject)
return
}
srv := c.srv
acc := c.acc
// Mostly under testing scenarios.
if srv == nil || acc == nil {
return
}
// Match the subscriptions. We will use our own L1 map if
// it's still valid, avoiding contention on the shared sublist.
var r *SublistResult
var ok bool
genid := atomic.LoadUint64(&c.acc.sl.genid)
if genid == c.in.genid && c.in.results != nil {
r, ok = c.in.results[string(c.pa.subject)]
} else {
// Reset our L1 completely.
c.in.results = make(map[string]*SublistResult)
c.in.genid = genid
}
// Go back to the sublist data structure.
if !ok {
r = c.acc.sl.Match(string(c.pa.subject))
c.in.results[string(c.pa.subject)] = r
// Prune the results cache. Keeps us from unbounded growth. Random delete.
if len(c.in.results) > maxResultCacheSize {
n := 0
for subject := range c.in.results {
delete(c.in.results, subject)
if n++; n > pruneSize {
break
}
}
}
}
// Check to see if we need to map/route to another account.
if acc.imports.services != nil {
c.checkForImportServices(acc, msg)
}
// Collect queue names if needed.
var qnames [][]byte
// Check for no interest, short circuit if so.
// This is the fanout scale.
if len(r.psubs)+len(r.qsubs) > 0 {
flag := pmrNoFlag
// If we have queue subs in this cluster, then if we run in gateway
// mode and the remote gateways have queue subs, then we need to
// collect the queue groups this message was sent to so that we
// exclude them when sending to gateways.
if len(r.qsubs) > 0 && c.srv.gateway.enabled &&
atomic.LoadInt64(&c.srv.gateway.totalQSubs) > 0 {
flag = pmrCollectQueueNames
}
qnames = c.processMsgResults(acc, r, msg, c.pa.subject, c.pa.reply, flag)
}
// Now deal with gateways
if c.srv.gateway.enabled {
c.sendMsgToGateways(c.acc, msg, c.pa.subject, c.pa.reply, qnames)
}
} | [
"func",
"(",
"c",
"*",
"client",
")",
"processInboundLeafMsg",
"(",
"msg",
"[",
"]",
"byte",
")",
"{",
"// Update statistics",
"c",
".",
"in",
".",
"msgs",
"++",
"\n",
"// The msg includes the CR_LF, so pull back out for accounting.",
"c",
".",
"in",
".",
"bytes... | // processInboundLeafMsg is called to process an inbound msg from a leaf node. | [
"processInboundLeafMsg",
"is",
"called",
"to",
"process",
"an",
"inbound",
"msg",
"from",
"a",
"leaf",
"node",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L1190-L1271 |
164,383 | nats-io/gnatsd | server/leafnode.go | protoChunks | func protoChunks(b []byte, csz int) [][]byte {
if b == nil {
return nil
}
if len(b) <= csz {
return [][]byte{b}
}
var (
chunks [][]byte
start int
)
for i := csz; i < len(b); {
// Walk forward to find a CR_LF
delim := bytes.Index(b[i:], []byte(CR_LF))
if delim < 0 {
chunks = append(chunks, b[start:])
break
}
end := delim + LEN_CR_LF + i
chunks = append(chunks, b[start:end])
start = end
i = end + csz
}
return chunks
} | go | func protoChunks(b []byte, csz int) [][]byte {
if b == nil {
return nil
}
if len(b) <= csz {
return [][]byte{b}
}
var (
chunks [][]byte
start int
)
for i := csz; i < len(b); {
// Walk forward to find a CR_LF
delim := bytes.Index(b[i:], []byte(CR_LF))
if delim < 0 {
chunks = append(chunks, b[start:])
break
}
end := delim + LEN_CR_LF + i
chunks = append(chunks, b[start:end])
start = end
i = end + csz
}
return chunks
} | [
"func",
"protoChunks",
"(",
"b",
"[",
"]",
"byte",
",",
"csz",
"int",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"if",
"b",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"len",
"(",
"b",
")",
"<=",
"csz",
"{",
"return",
"[",
"]",
"["... | // This functional will take a larger buffer and break it into
// chunks that are protocol correct. Reason being is that we are
// doing this in the first place to get things in smaller sizes
// out the door but we may allow someone to get in between us as
// we do.
// NOTE - currently this does not process MSG protos. | [
"This",
"functional",
"will",
"take",
"a",
"larger",
"buffer",
"and",
"break",
"it",
"into",
"chunks",
"that",
"are",
"protocol",
"correct",
".",
"Reason",
"being",
"is",
"that",
"we",
"are",
"doing",
"this",
"in",
"the",
"first",
"place",
"to",
"get",
"... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/leafnode.go#L1279-L1303 |
164,384 | nats-io/gnatsd | server/auth.go | clone | func (u *User) clone() *User {
if u == nil {
return nil
}
clone := &User{}
*clone = *u
clone.Permissions = u.Permissions.clone()
return clone
} | go | func (u *User) clone() *User {
if u == nil {
return nil
}
clone := &User{}
*clone = *u
clone.Permissions = u.Permissions.clone()
return clone
} | [
"func",
"(",
"u",
"*",
"User",
")",
"clone",
"(",
")",
"*",
"User",
"{",
"if",
"u",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"clone",
":=",
"&",
"User",
"{",
"}",
"\n",
"*",
"clone",
"=",
"*",
"u",
"\n",
"clone",
".",
"Permissions"... | // clone performs a deep copy of the User struct, returning a new clone with
// all values copied. | [
"clone",
"performs",
"a",
"deep",
"copy",
"of",
"the",
"User",
"struct",
"returning",
"a",
"new",
"clone",
"with",
"all",
"values",
"copied",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/auth.go#L63-L71 |
164,385 | nats-io/gnatsd | server/auth.go | clone | func (n *NkeyUser) clone() *NkeyUser {
if n == nil {
return nil
}
clone := &NkeyUser{}
*clone = *n
clone.Permissions = n.Permissions.clone()
return clone
} | go | func (n *NkeyUser) clone() *NkeyUser {
if n == nil {
return nil
}
clone := &NkeyUser{}
*clone = *n
clone.Permissions = n.Permissions.clone()
return clone
} | [
"func",
"(",
"n",
"*",
"NkeyUser",
")",
"clone",
"(",
")",
"*",
"NkeyUser",
"{",
"if",
"n",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"clone",
":=",
"&",
"NkeyUser",
"{",
"}",
"\n",
"*",
"clone",
"=",
"*",
"n",
"\n",
"clone",
".",
"... | // clone performs a deep copy of the NkeyUser struct, returning a new clone with
// all values copied. | [
"clone",
"performs",
"a",
"deep",
"copy",
"of",
"the",
"NkeyUser",
"struct",
"returning",
"a",
"new",
"clone",
"with",
"all",
"values",
"copied",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/auth.go#L75-L83 |
164,386 | nats-io/gnatsd | server/auth.go | clone | func (p *SubjectPermission) clone() *SubjectPermission {
if p == nil {
return nil
}
clone := &SubjectPermission{}
if p.Allow != nil {
clone.Allow = make([]string, len(p.Allow))
copy(clone.Allow, p.Allow)
}
if p.Deny != nil {
clone.Deny = make([]string, len(p.Deny))
copy(clone.Deny, p.Deny)
}
return clone
} | go | func (p *SubjectPermission) clone() *SubjectPermission {
if p == nil {
return nil
}
clone := &SubjectPermission{}
if p.Allow != nil {
clone.Allow = make([]string, len(p.Allow))
copy(clone.Allow, p.Allow)
}
if p.Deny != nil {
clone.Deny = make([]string, len(p.Deny))
copy(clone.Deny, p.Deny)
}
return clone
} | [
"func",
"(",
"p",
"*",
"SubjectPermission",
")",
"clone",
"(",
")",
"*",
"SubjectPermission",
"{",
"if",
"p",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"clone",
":=",
"&",
"SubjectPermission",
"{",
"}",
"\n",
"if",
"p",
".",
"Allow",
"!=",
... | // clone will clone an individual subject permission. | [
"clone",
"will",
"clone",
"an",
"individual",
"subject",
"permission",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/auth.go#L108-L122 |
164,387 | nats-io/gnatsd | server/auth.go | clone | func (p *Permissions) clone() *Permissions {
if p == nil {
return nil
}
clone := &Permissions{}
if p.Publish != nil {
clone.Publish = p.Publish.clone()
}
if p.Subscribe != nil {
clone.Subscribe = p.Subscribe.clone()
}
return clone
} | go | func (p *Permissions) clone() *Permissions {
if p == nil {
return nil
}
clone := &Permissions{}
if p.Publish != nil {
clone.Publish = p.Publish.clone()
}
if p.Subscribe != nil {
clone.Subscribe = p.Subscribe.clone()
}
return clone
} | [
"func",
"(",
"p",
"*",
"Permissions",
")",
"clone",
"(",
")",
"*",
"Permissions",
"{",
"if",
"p",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"clone",
":=",
"&",
"Permissions",
"{",
"}",
"\n",
"if",
"p",
".",
"Publish",
"!=",
"nil",
"{",
... | // clone performs a deep copy of the Permissions struct, returning a new clone
// with all values copied. | [
"clone",
"performs",
"a",
"deep",
"copy",
"of",
"the",
"Permissions",
"struct",
"returning",
"a",
"new",
"clone",
"with",
"all",
"values",
"copied",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/auth.go#L126-L138 |
164,388 | nats-io/gnatsd | server/auth.go | checkAuthforWarnings | func (s *Server) checkAuthforWarnings() {
warn := false
if s.opts.Password != "" && !isBcrypt(s.opts.Password) {
warn = true
}
for _, u := range s.users {
// Skip warn if using TLS certs based auth
// unless a password has been left in the config.
if u.Password == "" && s.opts.TLSMap {
continue
}
if !isBcrypt(u.Password) {
warn = true
break
}
}
if warn {
// Warning about using plaintext passwords.
s.Warnf("Plaintext passwords detected, use nkeys or bcrypt.")
}
} | go | func (s *Server) checkAuthforWarnings() {
warn := false
if s.opts.Password != "" && !isBcrypt(s.opts.Password) {
warn = true
}
for _, u := range s.users {
// Skip warn if using TLS certs based auth
// unless a password has been left in the config.
if u.Password == "" && s.opts.TLSMap {
continue
}
if !isBcrypt(u.Password) {
warn = true
break
}
}
if warn {
// Warning about using plaintext passwords.
s.Warnf("Plaintext passwords detected, use nkeys or bcrypt.")
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"checkAuthforWarnings",
"(",
")",
"{",
"warn",
":=",
"false",
"\n",
"if",
"s",
".",
"opts",
".",
"Password",
"!=",
"\"",
"\"",
"&&",
"!",
"isBcrypt",
"(",
"s",
".",
"opts",
".",
"Password",
")",
"{",
"warn",
... | // checkAuthforWarnings will look for insecure settings and log concerns.
// Lock is assumed held. | [
"checkAuthforWarnings",
"will",
"look",
"for",
"insecure",
"settings",
"and",
"log",
"concerns",
".",
"Lock",
"is",
"assumed",
"held",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/auth.go#L142-L163 |
164,389 | nats-io/gnatsd | server/auth.go | assignGlobalAccountToOrphanUsers | func (s *Server) assignGlobalAccountToOrphanUsers() {
for _, u := range s.users {
if u.Account == nil {
u.Account = s.gacc
}
}
for _, u := range s.nkeys {
if u.Account == nil {
u.Account = s.gacc
}
}
} | go | func (s *Server) assignGlobalAccountToOrphanUsers() {
for _, u := range s.users {
if u.Account == nil {
u.Account = s.gacc
}
}
for _, u := range s.nkeys {
if u.Account == nil {
u.Account = s.gacc
}
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"assignGlobalAccountToOrphanUsers",
"(",
")",
"{",
"for",
"_",
",",
"u",
":=",
"range",
"s",
".",
"users",
"{",
"if",
"u",
".",
"Account",
"==",
"nil",
"{",
"u",
".",
"Account",
"=",
"s",
".",
"gacc",
"\n",
"... | // If opts.Users or opts.Nkeys have definitions without an account
// defined assign them to the default global account.
// Lock should be held. | [
"If",
"opts",
".",
"Users",
"or",
"opts",
".",
"Nkeys",
"have",
"definitions",
"without",
"an",
"account",
"defined",
"assign",
"them",
"to",
"the",
"default",
"global",
"account",
".",
"Lock",
"should",
"be",
"held",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/auth.go#L168-L179 |
164,390 | nats-io/gnatsd | server/auth.go | configureAuthorization | func (s *Server) configureAuthorization() {
if s.opts == nil {
return
}
// Snapshot server options.
opts := s.getOpts()
// Check for multiple users first
// This just checks and sets up the user map if we have multiple users.
if opts.CustomClientAuthentication != nil {
s.info.AuthRequired = true
} else if len(s.trustedKeys) > 0 {
s.info.AuthRequired = true
} else if opts.Nkeys != nil || opts.Users != nil {
// Support both at the same time.
if opts.Nkeys != nil {
s.nkeys = make(map[string]*NkeyUser)
for _, u := range opts.Nkeys {
copy := u.clone()
if u.Account != nil {
if v, ok := s.accounts.Load(u.Account.Name); ok {
copy.Account = v.(*Account)
}
}
s.nkeys[u.Nkey] = copy
}
}
if opts.Users != nil {
s.users = make(map[string]*User)
for _, u := range opts.Users {
copy := u.clone()
if u.Account != nil {
if v, ok := s.accounts.Load(u.Account.Name); ok {
copy.Account = v.(*Account)
}
}
s.users[u.Username] = copy
}
}
s.assignGlobalAccountToOrphanUsers()
s.info.AuthRequired = true
} else if opts.Username != "" || opts.Authorization != "" {
s.info.AuthRequired = true
} else {
s.users = nil
s.info.AuthRequired = false
}
} | go | func (s *Server) configureAuthorization() {
if s.opts == nil {
return
}
// Snapshot server options.
opts := s.getOpts()
// Check for multiple users first
// This just checks and sets up the user map if we have multiple users.
if opts.CustomClientAuthentication != nil {
s.info.AuthRequired = true
} else if len(s.trustedKeys) > 0 {
s.info.AuthRequired = true
} else if opts.Nkeys != nil || opts.Users != nil {
// Support both at the same time.
if opts.Nkeys != nil {
s.nkeys = make(map[string]*NkeyUser)
for _, u := range opts.Nkeys {
copy := u.clone()
if u.Account != nil {
if v, ok := s.accounts.Load(u.Account.Name); ok {
copy.Account = v.(*Account)
}
}
s.nkeys[u.Nkey] = copy
}
}
if opts.Users != nil {
s.users = make(map[string]*User)
for _, u := range opts.Users {
copy := u.clone()
if u.Account != nil {
if v, ok := s.accounts.Load(u.Account.Name); ok {
copy.Account = v.(*Account)
}
}
s.users[u.Username] = copy
}
}
s.assignGlobalAccountToOrphanUsers()
s.info.AuthRequired = true
} else if opts.Username != "" || opts.Authorization != "" {
s.info.AuthRequired = true
} else {
s.users = nil
s.info.AuthRequired = false
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"configureAuthorization",
"(",
")",
"{",
"if",
"s",
".",
"opts",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Snapshot server options.",
"opts",
":=",
"s",
".",
"getOpts",
"(",
")",
"\n\n",
"// Check for multiple... | // configureAuthorization will do any setup needed for authorization.
// Lock is assumed held. | [
"configureAuthorization",
"will",
"do",
"any",
"setup",
"needed",
"for",
"authorization",
".",
"Lock",
"is",
"assumed",
"held",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/auth.go#L183-L231 |
164,391 | nats-io/gnatsd | server/auth.go | checkAuthentication | func (s *Server) checkAuthentication(c *client) bool {
switch c.kind {
case CLIENT:
return s.isClientAuthorized(c)
case ROUTER:
return s.isRouterAuthorized(c)
case GATEWAY:
return s.isGatewayAuthorized(c)
case LEAF:
return s.isLeafNodeAuthorized(c)
default:
return false
}
} | go | func (s *Server) checkAuthentication(c *client) bool {
switch c.kind {
case CLIENT:
return s.isClientAuthorized(c)
case ROUTER:
return s.isRouterAuthorized(c)
case GATEWAY:
return s.isGatewayAuthorized(c)
case LEAF:
return s.isLeafNodeAuthorized(c)
default:
return false
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"checkAuthentication",
"(",
"c",
"*",
"client",
")",
"bool",
"{",
"switch",
"c",
".",
"kind",
"{",
"case",
"CLIENT",
":",
"return",
"s",
".",
"isClientAuthorized",
"(",
"c",
")",
"\n",
"case",
"ROUTER",
":",
"ret... | // checkAuthentication will check based on client type and
// return boolean indicating if client is authorized. | [
"checkAuthentication",
"will",
"check",
"based",
"on",
"client",
"type",
"and",
"return",
"boolean",
"indicating",
"if",
"client",
"is",
"authorized",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/auth.go#L235-L248 |
164,392 | nats-io/gnatsd | server/auth.go | isLeafNodeAuthorized | func (s *Server) isLeafNodeAuthorized(c *client) bool {
// FIXME(dlc) - This is duplicated from client auth, should be able to combine
// and not fail so bad on DRY.
// Grab under lock but process after.
var (
juc *jwt.UserClaims
acc *Account
err error
)
s.mu.Lock()
// Check if we have trustedKeys defined in the server. If so we require a user jwt.
if s.trustedKeys != nil {
if c.opts.JWT == "" {
s.mu.Unlock()
c.Debugf("Authentication requires a user JWT")
return false
}
// So we have a valid user jwt here.
juc, err = jwt.DecodeUserClaims(c.opts.JWT)
if err != nil {
s.mu.Unlock()
c.Debugf("User JWT not valid: %v", err)
return false
}
vr := jwt.CreateValidationResults()
juc.Validate(vr)
if vr.IsBlocking(true) {
s.mu.Unlock()
c.Debugf("User JWT no longer valid: %+v", vr)
return false
}
}
s.mu.Unlock()
// If we have a jwt and a userClaim, make sure we have the Account, etc associated.
// We need to look up the account. This will use an account resolver if one is present.
if juc != nil {
if acc, _ = s.LookupAccount(juc.Issuer); acc == nil {
c.Debugf("Account JWT can not be found")
return false
}
// FIXME(dlc) - Add in check for account allowed to do leaf nodes?
// Bool or active count like client?
if !s.isTrustedIssuer(acc.Issuer) {
c.Debugf("Account JWT not signed by trusted operator")
return false
}
if acc.IsExpired() {
c.Debugf("Account JWT has expired")
return false
}
// Verify the signature against the nonce.
if c.opts.Sig == "" {
c.Debugf("Signature missing")
return false
}
sig, err := base64.RawURLEncoding.DecodeString(c.opts.Sig)
if err != nil {
// Allow fallback to normal base64.
sig, err = base64.StdEncoding.DecodeString(c.opts.Sig)
if err != nil {
c.Debugf("Signature not valid base64")
return false
}
}
pub, err := nkeys.FromPublicKey(juc.Subject)
if err != nil {
c.Debugf("User nkey not valid: %v", err)
return false
}
if err := pub.Verify(c.nonce, sig); err != nil {
c.Debugf("Signature not verified")
return false
}
nkey := buildInternalNkeyUser(juc, acc)
if err := c.RegisterNkeyUser(nkey); err != nil {
return false
}
// Check if we need to set an auth timer if the user jwt expires.
c.checkExpiration(juc.Claims())
return true
}
// For now this means we are binding the leafnode to the global account.
c.registerWithAccount(s.globalAccount())
// Snapshot server options.
opts := s.getOpts()
if opts.LeafNode.Username == "" {
return true
}
if opts.LeafNode.Username != c.opts.Username {
return false
}
return comparePasswords(opts.LeafNode.Password, c.opts.Password)
} | go | func (s *Server) isLeafNodeAuthorized(c *client) bool {
// FIXME(dlc) - This is duplicated from client auth, should be able to combine
// and not fail so bad on DRY.
// Grab under lock but process after.
var (
juc *jwt.UserClaims
acc *Account
err error
)
s.mu.Lock()
// Check if we have trustedKeys defined in the server. If so we require a user jwt.
if s.trustedKeys != nil {
if c.opts.JWT == "" {
s.mu.Unlock()
c.Debugf("Authentication requires a user JWT")
return false
}
// So we have a valid user jwt here.
juc, err = jwt.DecodeUserClaims(c.opts.JWT)
if err != nil {
s.mu.Unlock()
c.Debugf("User JWT not valid: %v", err)
return false
}
vr := jwt.CreateValidationResults()
juc.Validate(vr)
if vr.IsBlocking(true) {
s.mu.Unlock()
c.Debugf("User JWT no longer valid: %+v", vr)
return false
}
}
s.mu.Unlock()
// If we have a jwt and a userClaim, make sure we have the Account, etc associated.
// We need to look up the account. This will use an account resolver if one is present.
if juc != nil {
if acc, _ = s.LookupAccount(juc.Issuer); acc == nil {
c.Debugf("Account JWT can not be found")
return false
}
// FIXME(dlc) - Add in check for account allowed to do leaf nodes?
// Bool or active count like client?
if !s.isTrustedIssuer(acc.Issuer) {
c.Debugf("Account JWT not signed by trusted operator")
return false
}
if acc.IsExpired() {
c.Debugf("Account JWT has expired")
return false
}
// Verify the signature against the nonce.
if c.opts.Sig == "" {
c.Debugf("Signature missing")
return false
}
sig, err := base64.RawURLEncoding.DecodeString(c.opts.Sig)
if err != nil {
// Allow fallback to normal base64.
sig, err = base64.StdEncoding.DecodeString(c.opts.Sig)
if err != nil {
c.Debugf("Signature not valid base64")
return false
}
}
pub, err := nkeys.FromPublicKey(juc.Subject)
if err != nil {
c.Debugf("User nkey not valid: %v", err)
return false
}
if err := pub.Verify(c.nonce, sig); err != nil {
c.Debugf("Signature not verified")
return false
}
nkey := buildInternalNkeyUser(juc, acc)
if err := c.RegisterNkeyUser(nkey); err != nil {
return false
}
// Check if we need to set an auth timer if the user jwt expires.
c.checkExpiration(juc.Claims())
return true
}
// For now this means we are binding the leafnode to the global account.
c.registerWithAccount(s.globalAccount())
// Snapshot server options.
opts := s.getOpts()
if opts.LeafNode.Username == "" {
return true
}
if opts.LeafNode.Username != c.opts.Username {
return false
}
return comparePasswords(opts.LeafNode.Password, c.opts.Password)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"isLeafNodeAuthorized",
"(",
"c",
"*",
"client",
")",
"bool",
"{",
"// FIXME(dlc) - This is duplicated from client auth, should be able to combine",
"// and not fail so bad on DRY.",
"// Grab under lock but process after.",
"var",
"(",
"juc... | // isLeafNodeAuthorized will check for auth for an inbound leaf node connection. | [
"isLeafNodeAuthorized",
"will",
"check",
"for",
"auth",
"for",
"an",
"inbound",
"leaf",
"node",
"connection",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/auth.go#L558-L659 |
164,393 | nats-io/gnatsd | server/log.go | ConfigureLogger | func (s *Server) ConfigureLogger() {
var (
log Logger
// Snapshot server options.
opts = s.getOpts()
)
if opts.NoLog {
return
}
syslog := opts.Syslog
if isWindowsService() && opts.LogFile == "" {
// Enable syslog if no log file is specified and we're running as a
// Windows service so that logs are written to the Windows event log.
syslog = true
}
if opts.LogFile != "" {
log = srvlog.NewFileLogger(opts.LogFile, opts.Logtime, opts.Debug, opts.Trace, true)
} else if opts.RemoteSyslog != "" {
log = srvlog.NewRemoteSysLogger(opts.RemoteSyslog, opts.Debug, opts.Trace)
} else if syslog {
log = srvlog.NewSysLogger(opts.Debug, opts.Trace)
} else {
colors := true
// Check to see if stderr is being redirected and if so turn off color
// Also turn off colors if we're running on Windows where os.Stderr.Stat() returns an invalid handle-error
stat, err := os.Stderr.Stat()
if err != nil || (stat.Mode()&os.ModeCharDevice) == 0 {
colors = false
}
log = srvlog.NewStdLogger(opts.Logtime, opts.Debug, opts.Trace, colors, true)
}
s.SetLogger(log, opts.Debug, opts.Trace)
} | go | func (s *Server) ConfigureLogger() {
var (
log Logger
// Snapshot server options.
opts = s.getOpts()
)
if opts.NoLog {
return
}
syslog := opts.Syslog
if isWindowsService() && opts.LogFile == "" {
// Enable syslog if no log file is specified and we're running as a
// Windows service so that logs are written to the Windows event log.
syslog = true
}
if opts.LogFile != "" {
log = srvlog.NewFileLogger(opts.LogFile, opts.Logtime, opts.Debug, opts.Trace, true)
} else if opts.RemoteSyslog != "" {
log = srvlog.NewRemoteSysLogger(opts.RemoteSyslog, opts.Debug, opts.Trace)
} else if syslog {
log = srvlog.NewSysLogger(opts.Debug, opts.Trace)
} else {
colors := true
// Check to see if stderr is being redirected and if so turn off color
// Also turn off colors if we're running on Windows where os.Stderr.Stat() returns an invalid handle-error
stat, err := os.Stderr.Stat()
if err != nil || (stat.Mode()&os.ModeCharDevice) == 0 {
colors = false
}
log = srvlog.NewStdLogger(opts.Logtime, opts.Debug, opts.Trace, colors, true)
}
s.SetLogger(log, opts.Debug, opts.Trace)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ConfigureLogger",
"(",
")",
"{",
"var",
"(",
"log",
"Logger",
"\n\n",
"// Snapshot server options.",
"opts",
"=",
"s",
".",
"getOpts",
"(",
")",
"\n",
")",
"\n\n",
"if",
"opts",
".",
"NoLog",
"{",
"return",
"\n",
... | // ConfigureLogger configures and sets the logger for the server. | [
"ConfigureLogger",
"configures",
"and",
"sets",
"the",
"logger",
"for",
"the",
"server",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/log.go#L47-L84 |
164,394 | nats-io/gnatsd | server/log.go | SetLogger | func (s *Server) SetLogger(logger Logger, debugFlag, traceFlag bool) {
if debugFlag {
atomic.StoreInt32(&s.logging.debug, 1)
} else {
atomic.StoreInt32(&s.logging.debug, 0)
}
if traceFlag {
atomic.StoreInt32(&s.logging.trace, 1)
} else {
atomic.StoreInt32(&s.logging.trace, 0)
}
s.logging.Lock()
if s.logging.logger != nil {
// Check to see if the logger implements io.Closer. This could be a
// logger from another process embedding the NATS server or a dummy
// test logger that may not implement that interface.
if l, ok := s.logging.logger.(io.Closer); ok {
if err := l.Close(); err != nil {
s.Errorf("Error closing logger: %v", err)
}
}
}
s.logging.logger = logger
s.logging.Unlock()
} | go | func (s *Server) SetLogger(logger Logger, debugFlag, traceFlag bool) {
if debugFlag {
atomic.StoreInt32(&s.logging.debug, 1)
} else {
atomic.StoreInt32(&s.logging.debug, 0)
}
if traceFlag {
atomic.StoreInt32(&s.logging.trace, 1)
} else {
atomic.StoreInt32(&s.logging.trace, 0)
}
s.logging.Lock()
if s.logging.logger != nil {
// Check to see if the logger implements io.Closer. This could be a
// logger from another process embedding the NATS server or a dummy
// test logger that may not implement that interface.
if l, ok := s.logging.logger.(io.Closer); ok {
if err := l.Close(); err != nil {
s.Errorf("Error closing logger: %v", err)
}
}
}
s.logging.logger = logger
s.logging.Unlock()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"SetLogger",
"(",
"logger",
"Logger",
",",
"debugFlag",
",",
"traceFlag",
"bool",
")",
"{",
"if",
"debugFlag",
"{",
"atomic",
".",
"StoreInt32",
"(",
"&",
"s",
".",
"logging",
".",
"debug",
",",
"1",
")",
"\n",
... | // SetLogger sets the logger of the server | [
"SetLogger",
"sets",
"the",
"logger",
"of",
"the",
"server"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/log.go#L87-L111 |
164,395 | nats-io/gnatsd | server/log.go | ReOpenLogFile | func (s *Server) ReOpenLogFile() {
// Check to make sure this is a file logger.
s.logging.RLock()
ll := s.logging.logger
s.logging.RUnlock()
if ll == nil {
s.Noticef("File log re-open ignored, no logger")
return
}
// Snapshot server options.
opts := s.getOpts()
if opts.LogFile == "" {
s.Noticef("File log re-open ignored, not a file logger")
} else {
fileLog := srvlog.NewFileLogger(opts.LogFile,
opts.Logtime, opts.Debug, opts.Trace, true)
s.SetLogger(fileLog, opts.Debug, opts.Trace)
s.Noticef("File log re-opened")
}
} | go | func (s *Server) ReOpenLogFile() {
// Check to make sure this is a file logger.
s.logging.RLock()
ll := s.logging.logger
s.logging.RUnlock()
if ll == nil {
s.Noticef("File log re-open ignored, no logger")
return
}
// Snapshot server options.
opts := s.getOpts()
if opts.LogFile == "" {
s.Noticef("File log re-open ignored, not a file logger")
} else {
fileLog := srvlog.NewFileLogger(opts.LogFile,
opts.Logtime, opts.Debug, opts.Trace, true)
s.SetLogger(fileLog, opts.Debug, opts.Trace)
s.Noticef("File log re-opened")
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ReOpenLogFile",
"(",
")",
"{",
"// Check to make sure this is a file logger.",
"s",
".",
"logging",
".",
"RLock",
"(",
")",
"\n",
"ll",
":=",
"s",
".",
"logging",
".",
"logger",
"\n",
"s",
".",
"logging",
".",
"RUnl... | // ReOpenLogFile if the logger is a file based logger, close and re-open the file.
// This allows for file rotation by 'mv'ing the file then signaling
// the process to trigger this function. | [
"ReOpenLogFile",
"if",
"the",
"logger",
"is",
"a",
"file",
"based",
"logger",
"close",
"and",
"re",
"-",
"open",
"the",
"file",
".",
"This",
"allows",
"for",
"file",
"rotation",
"by",
"mv",
"ing",
"the",
"file",
"then",
"signaling",
"the",
"process",
"to... | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/log.go#L116-L138 |
164,396 | nats-io/gnatsd | server/monitor.go | fill | func (ci *ConnInfo) fill(client *client, nc net.Conn, now time.Time) {
ci.Cid = client.cid
ci.Start = client.start
ci.LastActivity = client.last
ci.Uptime = myUptime(now.Sub(client.start))
ci.Idle = myUptime(now.Sub(client.last))
ci.RTT = client.getRTT()
ci.OutMsgs = client.outMsgs
ci.OutBytes = client.outBytes
ci.NumSubs = uint32(len(client.subs))
ci.Pending = int(client.out.pb)
ci.Name = client.opts.Name
ci.Lang = client.opts.Lang
ci.Version = client.opts.Version
// inMsgs and inBytes are updated outside of the client's lock, so
// we need to use atomic here.
ci.InMsgs = atomic.LoadInt64(&client.inMsgs)
ci.InBytes = atomic.LoadInt64(&client.inBytes)
// If the connection is gone, too bad, we won't set TLSVersion and TLSCipher.
// Exclude clients that are still doing handshake so we don't block in
// ConnectionState().
if client.flags.isSet(handshakeComplete) && nc != nil {
conn := nc.(*tls.Conn)
cs := conn.ConnectionState()
ci.TLSVersion = tlsVersion(cs.Version)
ci.TLSCipher = tlsCipher(cs.CipherSuite)
}
if client.port != 0 {
ci.Port = int(client.port)
ci.IP = client.host
}
} | go | func (ci *ConnInfo) fill(client *client, nc net.Conn, now time.Time) {
ci.Cid = client.cid
ci.Start = client.start
ci.LastActivity = client.last
ci.Uptime = myUptime(now.Sub(client.start))
ci.Idle = myUptime(now.Sub(client.last))
ci.RTT = client.getRTT()
ci.OutMsgs = client.outMsgs
ci.OutBytes = client.outBytes
ci.NumSubs = uint32(len(client.subs))
ci.Pending = int(client.out.pb)
ci.Name = client.opts.Name
ci.Lang = client.opts.Lang
ci.Version = client.opts.Version
// inMsgs and inBytes are updated outside of the client's lock, so
// we need to use atomic here.
ci.InMsgs = atomic.LoadInt64(&client.inMsgs)
ci.InBytes = atomic.LoadInt64(&client.inBytes)
// If the connection is gone, too bad, we won't set TLSVersion and TLSCipher.
// Exclude clients that are still doing handshake so we don't block in
// ConnectionState().
if client.flags.isSet(handshakeComplete) && nc != nil {
conn := nc.(*tls.Conn)
cs := conn.ConnectionState()
ci.TLSVersion = tlsVersion(cs.Version)
ci.TLSCipher = tlsCipher(cs.CipherSuite)
}
if client.port != 0 {
ci.Port = int(client.port)
ci.IP = client.host
}
} | [
"func",
"(",
"ci",
"*",
"ConnInfo",
")",
"fill",
"(",
"client",
"*",
"client",
",",
"nc",
"net",
".",
"Conn",
",",
"now",
"time",
".",
"Time",
")",
"{",
"ci",
".",
"Cid",
"=",
"client",
".",
"cid",
"\n",
"ci",
".",
"Start",
"=",
"client",
".",
... | // Fills in the ConnInfo from the client.
// client should be locked. | [
"Fills",
"in",
"the",
"ConnInfo",
"from",
"the",
"client",
".",
"client",
"should",
"be",
"locked",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L357-L390 |
164,397 | nats-io/gnatsd | server/monitor.go | getRTT | func (c *client) getRTT() string {
if c.rtt == 0 {
// If a real client, go ahead and send ping now to get a value
// for RTT. For tests and telnet, or if client is closing, etc skip.
if !c.flags.isSet(clearConnection) && c.flags.isSet(connectReceived) && c.opts.Lang != "" {
c.sendPing()
}
return ""
}
var rtt time.Duration
if c.rtt > time.Microsecond && c.rtt < time.Millisecond {
rtt = c.rtt.Truncate(time.Microsecond)
} else {
rtt = c.rtt.Truncate(time.Millisecond)
}
return rtt.String()
} | go | func (c *client) getRTT() string {
if c.rtt == 0 {
// If a real client, go ahead and send ping now to get a value
// for RTT. For tests and telnet, or if client is closing, etc skip.
if !c.flags.isSet(clearConnection) && c.flags.isSet(connectReceived) && c.opts.Lang != "" {
c.sendPing()
}
return ""
}
var rtt time.Duration
if c.rtt > time.Microsecond && c.rtt < time.Millisecond {
rtt = c.rtt.Truncate(time.Microsecond)
} else {
rtt = c.rtt.Truncate(time.Millisecond)
}
return rtt.String()
} | [
"func",
"(",
"c",
"*",
"client",
")",
"getRTT",
"(",
")",
"string",
"{",
"if",
"c",
".",
"rtt",
"==",
"0",
"{",
"// If a real client, go ahead and send ping now to get a value",
"// for RTT. For tests and telnet, or if client is closing, etc skip.",
"if",
"!",
"c",
".",... | // Assume lock is held | [
"Assume",
"lock",
"is",
"held"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L393-L409 |
164,398 | nats-io/gnatsd | server/monitor.go | HandleConnz | func (s *Server) HandleConnz(w http.ResponseWriter, r *http.Request) {
sortOpt := SortOpt(r.URL.Query().Get("sort"))
auth, err := decodeBool(w, r, "auth")
if err != nil {
return
}
subs, err := decodeBool(w, r, "subs")
if err != nil {
return
}
offset, err := decodeInt(w, r, "offset")
if err != nil {
return
}
limit, err := decodeInt(w, r, "limit")
if err != nil {
return
}
cid, err := decodeUint64(w, r, "cid")
if err != nil {
return
}
state, err := decodeState(w, r)
if err != nil {
return
}
connzOpts := &ConnzOptions{
Sort: sortOpt,
Username: auth,
Subscriptions: subs,
Offset: offset,
Limit: limit,
CID: cid,
State: state,
}
s.mu.Lock()
s.httpReqStats[ConnzPath]++
s.mu.Unlock()
c, err := s.Connz(connzOpts)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
b, err := json.MarshalIndent(c, "", " ")
if err != nil {
s.Errorf("Error marshaling response to /connz request: %v", err)
}
// Handle response
ResponseHandler(w, r, b)
} | go | func (s *Server) HandleConnz(w http.ResponseWriter, r *http.Request) {
sortOpt := SortOpt(r.URL.Query().Get("sort"))
auth, err := decodeBool(w, r, "auth")
if err != nil {
return
}
subs, err := decodeBool(w, r, "subs")
if err != nil {
return
}
offset, err := decodeInt(w, r, "offset")
if err != nil {
return
}
limit, err := decodeInt(w, r, "limit")
if err != nil {
return
}
cid, err := decodeUint64(w, r, "cid")
if err != nil {
return
}
state, err := decodeState(w, r)
if err != nil {
return
}
connzOpts := &ConnzOptions{
Sort: sortOpt,
Username: auth,
Subscriptions: subs,
Offset: offset,
Limit: limit,
CID: cid,
State: state,
}
s.mu.Lock()
s.httpReqStats[ConnzPath]++
s.mu.Unlock()
c, err := s.Connz(connzOpts)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
b, err := json.MarshalIndent(c, "", " ")
if err != nil {
s.Errorf("Error marshaling response to /connz request: %v", err)
}
// Handle response
ResponseHandler(w, r, b)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"HandleConnz",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"sortOpt",
":=",
"SortOpt",
"(",
"r",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
... | // HandleConnz process HTTP requests for connection information. | [
"HandleConnz",
"process",
"HTTP",
"requests",
"for",
"connection",
"information",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L474-L528 |
164,399 | nats-io/gnatsd | server/monitor.go | Routez | func (s *Server) Routez(routezOpts *RoutezOptions) (*Routez, error) {
rs := &Routez{Routes: []*RouteInfo{}}
rs.Now = time.Now()
subs := routezOpts != nil && routezOpts.Subscriptions
s.mu.Lock()
rs.NumRoutes = len(s.routes)
// copy the server id for monitoring
rs.ID = s.info.ID
// Check for defined permissions for all connected routes.
if perms := s.getOpts().Cluster.Permissions; perms != nil {
rs.Import = perms.Import
rs.Export = perms.Export
}
// Walk the list
for _, r := range s.routes {
r.mu.Lock()
ri := &RouteInfo{
Rid: r.cid,
RemoteID: r.route.remoteID,
DidSolicit: r.route.didSolicit,
IsConfigured: r.route.routeType == Explicit,
InMsgs: atomic.LoadInt64(&r.inMsgs),
OutMsgs: r.outMsgs,
InBytes: atomic.LoadInt64(&r.inBytes),
OutBytes: r.outBytes,
NumSubs: uint32(len(r.subs)),
Import: r.opts.Import,
Export: r.opts.Export,
}
if subs && len(r.subs) > 0 {
ri.Subs = make([]string, 0, len(r.subs))
for _, sub := range r.subs {
ri.Subs = append(ri.Subs, string(sub.subject))
}
}
switch conn := r.nc.(type) {
case *net.TCPConn, *tls.Conn:
addr := conn.RemoteAddr().(*net.TCPAddr)
ri.Port = addr.Port
ri.IP = addr.IP.String()
}
r.mu.Unlock()
rs.Routes = append(rs.Routes, ri)
}
s.mu.Unlock()
return rs, nil
} | go | func (s *Server) Routez(routezOpts *RoutezOptions) (*Routez, error) {
rs := &Routez{Routes: []*RouteInfo{}}
rs.Now = time.Now()
subs := routezOpts != nil && routezOpts.Subscriptions
s.mu.Lock()
rs.NumRoutes = len(s.routes)
// copy the server id for monitoring
rs.ID = s.info.ID
// Check for defined permissions for all connected routes.
if perms := s.getOpts().Cluster.Permissions; perms != nil {
rs.Import = perms.Import
rs.Export = perms.Export
}
// Walk the list
for _, r := range s.routes {
r.mu.Lock()
ri := &RouteInfo{
Rid: r.cid,
RemoteID: r.route.remoteID,
DidSolicit: r.route.didSolicit,
IsConfigured: r.route.routeType == Explicit,
InMsgs: atomic.LoadInt64(&r.inMsgs),
OutMsgs: r.outMsgs,
InBytes: atomic.LoadInt64(&r.inBytes),
OutBytes: r.outBytes,
NumSubs: uint32(len(r.subs)),
Import: r.opts.Import,
Export: r.opts.Export,
}
if subs && len(r.subs) > 0 {
ri.Subs = make([]string, 0, len(r.subs))
for _, sub := range r.subs {
ri.Subs = append(ri.Subs, string(sub.subject))
}
}
switch conn := r.nc.(type) {
case *net.TCPConn, *tls.Conn:
addr := conn.RemoteAddr().(*net.TCPAddr)
ri.Port = addr.Port
ri.IP = addr.IP.String()
}
r.mu.Unlock()
rs.Routes = append(rs.Routes, ri)
}
s.mu.Unlock()
return rs, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Routez",
"(",
"routezOpts",
"*",
"RoutezOptions",
")",
"(",
"*",
"Routez",
",",
"error",
")",
"{",
"rs",
":=",
"&",
"Routez",
"{",
"Routes",
":",
"[",
"]",
"*",
"RouteInfo",
"{",
"}",
"}",
"\n",
"rs",
".",
... | // Routez returns a Routez struct containing inormation about routes. | [
"Routez",
"returns",
"a",
"Routez",
"struct",
"containing",
"inormation",
"about",
"routes",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor.go#L566-L618 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.