id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
164,000 | confluentinc/confluent-kafka-go | kafka/consumer.go | QueryWatermarkOffsets | func (c *Consumer) QueryWatermarkOffsets(topic string, partition int32, timeoutMs int) (low, high int64, err error) {
return queryWatermarkOffsets(c, topic, partition, timeoutMs)
} | go | func (c *Consumer) QueryWatermarkOffsets(topic string, partition int32, timeoutMs int) (low, high int64, err error) {
return queryWatermarkOffsets(c, topic, partition, timeoutMs)
} | [
"func",
"(",
"c",
"*",
"Consumer",
")",
"QueryWatermarkOffsets",
"(",
"topic",
"string",
",",
"partition",
"int32",
",",
"timeoutMs",
"int",
")",
"(",
"low",
",",
"high",
"int64",
",",
"err",
"error",
")",
"{",
"return",
"queryWatermarkOffsets",
"(",
"c",
",",
"topic",
",",
"partition",
",",
"timeoutMs",
")",
"\n",
"}"
] | // QueryWatermarkOffsets queries the broker for the low and high offsets for the given topic and partition. | [
"QueryWatermarkOffsets",
"queries",
"the",
"broker",
"for",
"the",
"low",
"and",
"high",
"offsets",
"for",
"the",
"given",
"topic",
"and",
"partition",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/consumer.go#L486-L488 |
164,001 | confluentinc/confluent-kafka-go | kafka/consumer.go | GetWatermarkOffsets | func (c *Consumer) GetWatermarkOffsets(topic string, partition int32) (low, high int64, err error) {
return getWatermarkOffsets(c, topic, partition)
} | go | func (c *Consumer) GetWatermarkOffsets(topic string, partition int32) (low, high int64, err error) {
return getWatermarkOffsets(c, topic, partition)
} | [
"func",
"(",
"c",
"*",
"Consumer",
")",
"GetWatermarkOffsets",
"(",
"topic",
"string",
",",
"partition",
"int32",
")",
"(",
"low",
",",
"high",
"int64",
",",
"err",
"error",
")",
"{",
"return",
"getWatermarkOffsets",
"(",
"c",
",",
"topic",
",",
"partition",
")",
"\n",
"}"
] | // GetWatermarkOffsets returns the cached low and high offsets for the given topic
// and partition. The high offset is populated on every fetch response or via calling QueryWatermarkOffsets.
// The low offset is populated every statistics.interval.ms if that value is set.
// OffsetInvalid will be returned if there is no cached offset for either value. | [
"GetWatermarkOffsets",
"returns",
"the",
"cached",
"low",
"and",
"high",
"offsets",
"for",
"the",
"given",
"topic",
"and",
"partition",
".",
"The",
"high",
"offset",
"is",
"populated",
"on",
"every",
"fetch",
"response",
"or",
"via",
"calling",
"QueryWatermarkOffsets",
".",
"The",
"low",
"offset",
"is",
"populated",
"every",
"statistics",
".",
"interval",
".",
"ms",
"if",
"that",
"value",
"is",
"set",
".",
"OffsetInvalid",
"will",
"be",
"returned",
"if",
"there",
"is",
"no",
"cached",
"offset",
"for",
"either",
"value",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/consumer.go#L494-L496 |
164,002 | confluentinc/confluent-kafka-go | kafka/consumer.go | Assignment | func (c *Consumer) Assignment() (partitions []TopicPartition, err error) {
var cParts *C.rd_kafka_topic_partition_list_t
cErr := C.rd_kafka_assignment(c.handle.rk, &cParts)
if cErr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newError(cErr)
}
defer C.rd_kafka_topic_partition_list_destroy(cParts)
partitions = newTopicPartitionsFromCparts(cParts)
return partitions, nil
} | go | func (c *Consumer) Assignment() (partitions []TopicPartition, err error) {
var cParts *C.rd_kafka_topic_partition_list_t
cErr := C.rd_kafka_assignment(c.handle.rk, &cParts)
if cErr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newError(cErr)
}
defer C.rd_kafka_topic_partition_list_destroy(cParts)
partitions = newTopicPartitionsFromCparts(cParts)
return partitions, nil
} | [
"func",
"(",
"c",
"*",
"Consumer",
")",
"Assignment",
"(",
")",
"(",
"partitions",
"[",
"]",
"TopicPartition",
",",
"err",
"error",
")",
"{",
"var",
"cParts",
"*",
"C",
".",
"rd_kafka_topic_partition_list_t",
"\n\n",
"cErr",
":=",
"C",
".",
"rd_kafka_assignment",
"(",
"c",
".",
"handle",
".",
"rk",
",",
"&",
"cParts",
")",
"\n",
"if",
"cErr",
"!=",
"C",
".",
"RD_KAFKA_RESP_ERR_NO_ERROR",
"{",
"return",
"nil",
",",
"newError",
"(",
"cErr",
")",
"\n",
"}",
"\n",
"defer",
"C",
".",
"rd_kafka_topic_partition_list_destroy",
"(",
"cParts",
")",
"\n\n",
"partitions",
"=",
"newTopicPartitionsFromCparts",
"(",
"cParts",
")",
"\n\n",
"return",
"partitions",
",",
"nil",
"\n",
"}"
] | // Assignment returns the current partition assignments | [
"Assignment",
"returns",
"the",
"current",
"partition",
"assignments"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/consumer.go#L538-L550 |
164,003 | confluentinc/confluent-kafka-go | kafka/consumer.go | Committed | func (c *Consumer) Committed(partitions []TopicPartition, timeoutMs int) (offsets []TopicPartition, err error) {
cparts := newCPartsFromTopicPartitions(partitions)
defer C.rd_kafka_topic_partition_list_destroy(cparts)
cerr := C.rd_kafka_committed(c.handle.rk, cparts, C.int(timeoutMs))
if cerr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newError(cerr)
}
return newTopicPartitionsFromCparts(cparts), nil
} | go | func (c *Consumer) Committed(partitions []TopicPartition, timeoutMs int) (offsets []TopicPartition, err error) {
cparts := newCPartsFromTopicPartitions(partitions)
defer C.rd_kafka_topic_partition_list_destroy(cparts)
cerr := C.rd_kafka_committed(c.handle.rk, cparts, C.int(timeoutMs))
if cerr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newError(cerr)
}
return newTopicPartitionsFromCparts(cparts), nil
} | [
"func",
"(",
"c",
"*",
"Consumer",
")",
"Committed",
"(",
"partitions",
"[",
"]",
"TopicPartition",
",",
"timeoutMs",
"int",
")",
"(",
"offsets",
"[",
"]",
"TopicPartition",
",",
"err",
"error",
")",
"{",
"cparts",
":=",
"newCPartsFromTopicPartitions",
"(",
"partitions",
")",
"\n",
"defer",
"C",
".",
"rd_kafka_topic_partition_list_destroy",
"(",
"cparts",
")",
"\n",
"cerr",
":=",
"C",
".",
"rd_kafka_committed",
"(",
"c",
".",
"handle",
".",
"rk",
",",
"cparts",
",",
"C",
".",
"int",
"(",
"timeoutMs",
")",
")",
"\n",
"if",
"cerr",
"!=",
"C",
".",
"RD_KAFKA_RESP_ERR_NO_ERROR",
"{",
"return",
"nil",
",",
"newError",
"(",
"cerr",
")",
"\n",
"}",
"\n\n",
"return",
"newTopicPartitionsFromCparts",
"(",
"cparts",
")",
",",
"nil",
"\n",
"}"
] | // Committed retrieves committed offsets for the given set of partitions | [
"Committed",
"retrieves",
"committed",
"offsets",
"for",
"the",
"given",
"set",
"of",
"partitions"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/consumer.go#L553-L562 |
164,004 | confluentinc/confluent-kafka-go | kafka/handle.go | waitTerminated | func (h *handle) waitTerminated(termCnt int) {
// Wait for termCnt termination-done events from goroutines
for ; termCnt > 0; termCnt-- {
_ = <-h.terminatedChan
}
} | go | func (h *handle) waitTerminated(termCnt int) {
// Wait for termCnt termination-done events from goroutines
for ; termCnt > 0; termCnt-- {
_ = <-h.terminatedChan
}
} | [
"func",
"(",
"h",
"*",
"handle",
")",
"waitTerminated",
"(",
"termCnt",
"int",
")",
"{",
"// Wait for termCnt termination-done events from goroutines",
"for",
";",
"termCnt",
">",
"0",
";",
"termCnt",
"--",
"{",
"_",
"=",
"<-",
"h",
".",
"terminatedChan",
"\n",
"}",
"\n",
"}"
] | // waitTerminated waits termination of background go-routines.
// termCnt is the number of goroutines expected to signal termination completion
// on h.terminatedChan | [
"waitTerminated",
"waits",
"termination",
"of",
"background",
"go",
"-",
"routines",
".",
"termCnt",
"is",
"the",
"number",
"of",
"goroutines",
"expected",
"to",
"signal",
"termination",
"completion",
"on",
"h",
".",
"terminatedChan"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/handle.go#L100-L105 |
164,005 | confluentinc/confluent-kafka-go | kafka/handle.go | getRkt0 | func (h *handle) getRkt0(topic string, ctopic *C.char, doLock bool) (crkt *C.rd_kafka_topic_t) {
if doLock {
h.rktCacheLock.Lock()
defer h.rktCacheLock.Unlock()
}
crkt, ok := h.rktCache[topic]
if ok {
return crkt
}
if ctopic == nil {
ctopic = C.CString(topic)
defer C.free(unsafe.Pointer(ctopic))
}
crkt = C.rd_kafka_topic_new(h.rk, ctopic, nil)
if crkt == nil {
panic(fmt.Sprintf("Unable to create new C topic \"%s\": %s",
topic, C.GoString(C.rd_kafka_err2str(C.rd_kafka_last_error()))))
}
h.rktCache[topic] = crkt
h.rktNameCache[crkt] = topic
return crkt
} | go | func (h *handle) getRkt0(topic string, ctopic *C.char, doLock bool) (crkt *C.rd_kafka_topic_t) {
if doLock {
h.rktCacheLock.Lock()
defer h.rktCacheLock.Unlock()
}
crkt, ok := h.rktCache[topic]
if ok {
return crkt
}
if ctopic == nil {
ctopic = C.CString(topic)
defer C.free(unsafe.Pointer(ctopic))
}
crkt = C.rd_kafka_topic_new(h.rk, ctopic, nil)
if crkt == nil {
panic(fmt.Sprintf("Unable to create new C topic \"%s\": %s",
topic, C.GoString(C.rd_kafka_err2str(C.rd_kafka_last_error()))))
}
h.rktCache[topic] = crkt
h.rktNameCache[crkt] = topic
return crkt
} | [
"func",
"(",
"h",
"*",
"handle",
")",
"getRkt0",
"(",
"topic",
"string",
",",
"ctopic",
"*",
"C",
".",
"char",
",",
"doLock",
"bool",
")",
"(",
"crkt",
"*",
"C",
".",
"rd_kafka_topic_t",
")",
"{",
"if",
"doLock",
"{",
"h",
".",
"rktCacheLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"rktCacheLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"crkt",
",",
"ok",
":=",
"h",
".",
"rktCache",
"[",
"topic",
"]",
"\n",
"if",
"ok",
"{",
"return",
"crkt",
"\n",
"}",
"\n\n",
"if",
"ctopic",
"==",
"nil",
"{",
"ctopic",
"=",
"C",
".",
"CString",
"(",
"topic",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"ctopic",
")",
")",
"\n",
"}",
"\n\n",
"crkt",
"=",
"C",
".",
"rd_kafka_topic_new",
"(",
"h",
".",
"rk",
",",
"ctopic",
",",
"nil",
")",
"\n",
"if",
"crkt",
"==",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"topic",
",",
"C",
".",
"GoString",
"(",
"C",
".",
"rd_kafka_err2str",
"(",
"C",
".",
"rd_kafka_last_error",
"(",
")",
")",
")",
")",
")",
"\n",
"}",
"\n\n",
"h",
".",
"rktCache",
"[",
"topic",
"]",
"=",
"crkt",
"\n",
"h",
".",
"rktNameCache",
"[",
"crkt",
"]",
"=",
"topic",
"\n\n",
"return",
"crkt",
"\n",
"}"
] | // getRkt0 finds or creates and returns a C topic_t object from the local cache. | [
"getRkt0",
"finds",
"or",
"creates",
"and",
"returns",
"a",
"C",
"topic_t",
"object",
"from",
"the",
"local",
"cache",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/handle.go#L108-L133 |
164,006 | confluentinc/confluent-kafka-go | kafka/handle.go | getRkt | func (h *handle) getRkt(topic string) (crkt *C.rd_kafka_topic_t) {
return h.getRkt0(topic, nil, true)
} | go | func (h *handle) getRkt(topic string) (crkt *C.rd_kafka_topic_t) {
return h.getRkt0(topic, nil, true)
} | [
"func",
"(",
"h",
"*",
"handle",
")",
"getRkt",
"(",
"topic",
"string",
")",
"(",
"crkt",
"*",
"C",
".",
"rd_kafka_topic_t",
")",
"{",
"return",
"h",
".",
"getRkt0",
"(",
"topic",
",",
"nil",
",",
"true",
")",
"\n",
"}"
] | // getRkt finds or creates and returns a C topic_t object from the local cache. | [
"getRkt",
"finds",
"or",
"creates",
"and",
"returns",
"a",
"C",
"topic_t",
"object",
"from",
"the",
"local",
"cache",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/handle.go#L136-L138 |
164,007 | confluentinc/confluent-kafka-go | kafka/handle.go | getTopicNameFromRkt | func (h *handle) getTopicNameFromRkt(crkt *C.rd_kafka_topic_t) (topic string) {
h.rktCacheLock.Lock()
defer h.rktCacheLock.Unlock()
topic, ok := h.rktNameCache[crkt]
if ok {
return topic
}
// we need our own copy/refcount of the crkt
ctopic := C.rd_kafka_topic_name(crkt)
topic = C.GoString(ctopic)
crkt = h.getRkt0(topic, ctopic, false /* dont lock */)
return topic
} | go | func (h *handle) getTopicNameFromRkt(crkt *C.rd_kafka_topic_t) (topic string) {
h.rktCacheLock.Lock()
defer h.rktCacheLock.Unlock()
topic, ok := h.rktNameCache[crkt]
if ok {
return topic
}
// we need our own copy/refcount of the crkt
ctopic := C.rd_kafka_topic_name(crkt)
topic = C.GoString(ctopic)
crkt = h.getRkt0(topic, ctopic, false /* dont lock */)
return topic
} | [
"func",
"(",
"h",
"*",
"handle",
")",
"getTopicNameFromRkt",
"(",
"crkt",
"*",
"C",
".",
"rd_kafka_topic_t",
")",
"(",
"topic",
"string",
")",
"{",
"h",
".",
"rktCacheLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"rktCacheLock",
".",
"Unlock",
"(",
")",
"\n\n",
"topic",
",",
"ok",
":=",
"h",
".",
"rktNameCache",
"[",
"crkt",
"]",
"\n",
"if",
"ok",
"{",
"return",
"topic",
"\n",
"}",
"\n\n",
"// we need our own copy/refcount of the crkt",
"ctopic",
":=",
"C",
".",
"rd_kafka_topic_name",
"(",
"crkt",
")",
"\n",
"topic",
"=",
"C",
".",
"GoString",
"(",
"ctopic",
")",
"\n\n",
"crkt",
"=",
"h",
".",
"getRkt0",
"(",
"topic",
",",
"ctopic",
",",
"false",
"/* dont lock */",
")",
"\n\n",
"return",
"topic",
"\n",
"}"
] | // getTopicNameFromRkt returns the topic name for a C topic_t object, preferably
// using the local cache to avoid a cgo call. | [
"getTopicNameFromRkt",
"returns",
"the",
"topic",
"name",
"for",
"a",
"C",
"topic_t",
"object",
"preferably",
"using",
"the",
"local",
"cache",
"to",
"avoid",
"a",
"cgo",
"call",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/handle.go#L142-L158 |
164,008 | confluentinc/confluent-kafka-go | kafka/handle.go | cgoGet | func (h *handle) cgoGet(cgoid int) (cg cgoif, found bool) {
if cgoid == 0 {
return nil, false
}
h.cgoLock.Lock()
defer h.cgoLock.Unlock()
cg, found = h.cgomap[cgoid]
if found {
delete(h.cgomap, cgoid)
}
return cg, found
} | go | func (h *handle) cgoGet(cgoid int) (cg cgoif, found bool) {
if cgoid == 0 {
return nil, false
}
h.cgoLock.Lock()
defer h.cgoLock.Unlock()
cg, found = h.cgomap[cgoid]
if found {
delete(h.cgomap, cgoid)
}
return cg, found
} | [
"func",
"(",
"h",
"*",
"handle",
")",
"cgoGet",
"(",
"cgoid",
"int",
")",
"(",
"cg",
"cgoif",
",",
"found",
"bool",
")",
"{",
"if",
"cgoid",
"==",
"0",
"{",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n\n",
"h",
".",
"cgoLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"h",
".",
"cgoLock",
".",
"Unlock",
"(",
")",
"\n",
"cg",
",",
"found",
"=",
"h",
".",
"cgomap",
"[",
"cgoid",
"]",
"\n",
"if",
"found",
"{",
"delete",
"(",
"h",
".",
"cgomap",
",",
"cgoid",
")",
"\n",
"}",
"\n\n",
"return",
"cg",
",",
"found",
"\n",
"}"
] | // cgoGet looks up cgoid in the cgo map, deletes the reference from the map
// and returns the object, if found. Else returns nil, false.
// Thread-safe. | [
"cgoGet",
"looks",
"up",
"cgoid",
"in",
"the",
"cgo",
"map",
"deletes",
"the",
"reference",
"from",
"the",
"map",
"and",
"returns",
"the",
"object",
"if",
"found",
".",
"Else",
"returns",
"nil",
"false",
".",
"Thread",
"-",
"safe",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/handle.go#L194-L207 |
164,009 | confluentinc/confluent-kafka-go | kafka/generated_errors.go | String | func (c ErrorCode) String() string {
return C.GoString(C.rd_kafka_err2str(C.rd_kafka_resp_err_t(c)))
} | go | func (c ErrorCode) String() string {
return C.GoString(C.rd_kafka_err2str(C.rd_kafka_resp_err_t(c)))
} | [
"func",
"(",
"c",
"ErrorCode",
")",
"String",
"(",
")",
"string",
"{",
"return",
"C",
".",
"GoString",
"(",
"C",
".",
"rd_kafka_err2str",
"(",
"C",
".",
"rd_kafka_resp_err_t",
"(",
"c",
")",
")",
")",
"\n",
"}"
] | // String returns a human readable representation of an error code | [
"String",
"returns",
"a",
"human",
"readable",
"representation",
"of",
"an",
"error",
"code"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/generated_errors.go#L14-L16 |
164,010 | confluentinc/confluent-kafka-go | kafka/header.go | String | func (h Header) String() string {
if h.Value == nil {
return fmt.Sprintf("%s=nil", h.Key)
}
valueLen := len(h.Value)
if valueLen == 0 {
return fmt.Sprintf("%s=<empty>", h.Key)
}
truncSize := valueLen
trunc := ""
if valueLen > 50+15 {
truncSize = 50
trunc = fmt.Sprintf("(%d more bytes)", valueLen-truncSize)
}
return fmt.Sprintf("%s=%s%s", h.Key, strconv.Quote(string(h.Value[:truncSize])), trunc)
} | go | func (h Header) String() string {
if h.Value == nil {
return fmt.Sprintf("%s=nil", h.Key)
}
valueLen := len(h.Value)
if valueLen == 0 {
return fmt.Sprintf("%s=<empty>", h.Key)
}
truncSize := valueLen
trunc := ""
if valueLen > 50+15 {
truncSize = 50
trunc = fmt.Sprintf("(%d more bytes)", valueLen-truncSize)
}
return fmt.Sprintf("%s=%s%s", h.Key, strconv.Quote(string(h.Value[:truncSize])), trunc)
} | [
"func",
"(",
"h",
"Header",
")",
"String",
"(",
")",
"string",
"{",
"if",
"h",
".",
"Value",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"h",
".",
"Key",
")",
"\n",
"}",
"\n\n",
"valueLen",
":=",
"len",
"(",
"h",
".",
"Value",
")",
"\n",
"if",
"valueLen",
"==",
"0",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"h",
".",
"Key",
")",
"\n",
"}",
"\n\n",
"truncSize",
":=",
"valueLen",
"\n",
"trunc",
":=",
"\"",
"\"",
"\n",
"if",
"valueLen",
">",
"50",
"+",
"15",
"{",
"truncSize",
"=",
"50",
"\n",
"trunc",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"valueLen",
"-",
"truncSize",
")",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"h",
".",
"Key",
",",
"strconv",
".",
"Quote",
"(",
"string",
"(",
"h",
".",
"Value",
"[",
":",
"truncSize",
"]",
")",
")",
",",
"trunc",
")",
"\n",
"}"
] | // String returns the Header Key and data in a human representable possibly truncated form
// suitable for displaying to the user. | [
"String",
"returns",
"the",
"Header",
"Key",
"and",
"data",
"in",
"a",
"human",
"representable",
"possibly",
"truncated",
"form",
"suitable",
"for",
"displaying",
"to",
"the",
"user",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/header.go#L49-L67 |
164,011 | confluentinc/confluent-kafka-go | kafka/adminapi.go | String | func (t TopicResult) String() string {
if t.Error.code == 0 {
return t.Topic
}
return fmt.Sprintf("%s (%s)", t.Topic, t.Error.str)
} | go | func (t TopicResult) String() string {
if t.Error.code == 0 {
return t.Topic
}
return fmt.Sprintf("%s (%s)", t.Topic, t.Error.str)
} | [
"func",
"(",
"t",
"TopicResult",
")",
"String",
"(",
")",
"string",
"{",
"if",
"t",
".",
"Error",
".",
"code",
"==",
"0",
"{",
"return",
"t",
".",
"Topic",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Topic",
",",
"t",
".",
"Error",
".",
"str",
")",
"\n",
"}"
] | // String returns a human-readable representation of a TopicResult. | [
"String",
"returns",
"a",
"human",
"-",
"readable",
"representation",
"of",
"a",
"TopicResult",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L76-L81 |
164,012 | confluentinc/confluent-kafka-go | kafka/adminapi.go | String | func (t ResourceType) String() string {
return C.GoString(C.rd_kafka_ResourceType_name(C.rd_kafka_ResourceType_t(t)))
} | go | func (t ResourceType) String() string {
return C.GoString(C.rd_kafka_ResourceType_name(C.rd_kafka_ResourceType_t(t)))
} | [
"func",
"(",
"t",
"ResourceType",
")",
"String",
"(",
")",
"string",
"{",
"return",
"C",
".",
"GoString",
"(",
"C",
".",
"rd_kafka_ResourceType_name",
"(",
"C",
".",
"rd_kafka_ResourceType_t",
"(",
"t",
")",
")",
")",
"\n",
"}"
] | // String returns the human-readable representation of a ResourceType | [
"String",
"returns",
"the",
"human",
"-",
"readable",
"representation",
"of",
"a",
"ResourceType"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L134-L136 |
164,013 | confluentinc/confluent-kafka-go | kafka/adminapi.go | String | func (t ConfigSource) String() string {
return C.GoString(C.rd_kafka_ConfigSource_name(C.rd_kafka_ConfigSource_t(t)))
} | go | func (t ConfigSource) String() string {
return C.GoString(C.rd_kafka_ConfigSource_name(C.rd_kafka_ConfigSource_t(t)))
} | [
"func",
"(",
"t",
"ConfigSource",
")",
"String",
"(",
")",
"string",
"{",
"return",
"C",
".",
"GoString",
"(",
"C",
".",
"rd_kafka_ConfigSource_name",
"(",
"C",
".",
"rd_kafka_ConfigSource_t",
"(",
"t",
")",
")",
")",
"\n",
"}"
] | // String returns the human-readable representation of a ConfigSource type | [
"String",
"returns",
"the",
"human",
"-",
"readable",
"representation",
"of",
"a",
"ConfigSource",
"type"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L174-L176 |
164,014 | confluentinc/confluent-kafka-go | kafka/adminapi.go | String | func (c ConfigResource) String() string {
return fmt.Sprintf("Resource(%s, %s)", c.Type, c.Name)
} | go | func (c ConfigResource) String() string {
return fmt.Sprintf("Resource(%s, %s)", c.Type, c.Name)
} | [
"func",
"(",
"c",
"ConfigResource",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Type",
",",
"c",
".",
"Name",
")",
"\n",
"}"
] | // String returns a human-readable representation of a ConfigResource | [
"String",
"returns",
"a",
"human",
"-",
"readable",
"representation",
"of",
"a",
"ConfigResource"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L192-L194 |
164,015 | confluentinc/confluent-kafka-go | kafka/adminapi.go | String | func (o AlterOperation) String() string {
switch o {
case AlterOperationSet:
return "Set"
default:
return fmt.Sprintf("Unknown%d?", int(o))
}
} | go | func (o AlterOperation) String() string {
switch o {
case AlterOperationSet:
return "Set"
default:
return fmt.Sprintf("Unknown%d?", int(o))
}
} | [
"func",
"(",
"o",
"AlterOperation",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"o",
"{",
"case",
"AlterOperationSet",
":",
"return",
"\"",
"\"",
"\n",
"default",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"int",
"(",
"o",
")",
")",
"\n",
"}",
"\n",
"}"
] | // String returns the human-readable representation of an AlterOperation | [
"String",
"returns",
"the",
"human",
"-",
"readable",
"representation",
"of",
"an",
"AlterOperation"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L206-L213 |
164,016 | confluentinc/confluent-kafka-go | kafka/adminapi.go | StringMapToConfigEntries | func StringMapToConfigEntries(stringMap map[string]string, operation AlterOperation) []ConfigEntry {
var ceList []ConfigEntry
for k, v := range stringMap {
ceList = append(ceList, ConfigEntry{Name: k, Value: v, Operation: operation})
}
return ceList
} | go | func StringMapToConfigEntries(stringMap map[string]string, operation AlterOperation) []ConfigEntry {
var ceList []ConfigEntry
for k, v := range stringMap {
ceList = append(ceList, ConfigEntry{Name: k, Value: v, Operation: operation})
}
return ceList
} | [
"func",
"StringMapToConfigEntries",
"(",
"stringMap",
"map",
"[",
"string",
"]",
"string",
",",
"operation",
"AlterOperation",
")",
"[",
"]",
"ConfigEntry",
"{",
"var",
"ceList",
"[",
"]",
"ConfigEntry",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"stringMap",
"{",
"ceList",
"=",
"append",
"(",
"ceList",
",",
"ConfigEntry",
"{",
"Name",
":",
"k",
",",
"Value",
":",
"v",
",",
"Operation",
":",
"operation",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"ceList",
"\n",
"}"
] | // StringMapToConfigEntries creates a new map of ConfigEntry objects from the
// provided string map. The AlterOperation is set on each created entry. | [
"StringMapToConfigEntries",
"creates",
"a",
"new",
"map",
"of",
"ConfigEntry",
"objects",
"from",
"the",
"provided",
"string",
"map",
".",
"The",
"AlterOperation",
"is",
"set",
"on",
"each",
"created",
"entry",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L227-L235 |
164,017 | confluentinc/confluent-kafka-go | kafka/adminapi.go | String | func (c ConfigEntry) String() string {
return fmt.Sprintf("%v %s=\"%s\"", c.Operation, c.Name, c.Value)
} | go | func (c ConfigEntry) String() string {
return fmt.Sprintf("%v %s=\"%s\"", c.Operation, c.Name, c.Value)
} | [
"func",
"(",
"c",
"ConfigEntry",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"c",
".",
"Operation",
",",
"c",
".",
"Name",
",",
"c",
".",
"Value",
")",
"\n",
"}"
] | // String returns a human-readable representation of a ConfigEntry. | [
"String",
"returns",
"a",
"human",
"-",
"readable",
"representation",
"of",
"a",
"ConfigEntry",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L238-L240 |
164,018 | confluentinc/confluent-kafka-go | kafka/adminapi.go | String | func (c ConfigEntryResult) String() string {
return fmt.Sprintf("%s=\"%s\"", c.Name, c.Value)
} | go | func (c ConfigEntryResult) String() string {
return fmt.Sprintf("%s=\"%s\"", c.Name, c.Value)
} | [
"func",
"(",
"c",
"ConfigEntryResult",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"c",
".",
"Name",
",",
"c",
".",
"Value",
")",
"\n",
"}"
] | // String returns a human-readable representation of a ConfigEntryResult. | [
"String",
"returns",
"a",
"human",
"-",
"readable",
"representation",
"of",
"a",
"ConfigEntryResult",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L262-L264 |
164,019 | confluentinc/confluent-kafka-go | kafka/adminapi.go | configEntryResultFromC | func configEntryResultFromC(cEntry *C.rd_kafka_ConfigEntry_t) (entry ConfigEntryResult) {
entry.Name = C.GoString(C.rd_kafka_ConfigEntry_name(cEntry))
cValue := C.rd_kafka_ConfigEntry_value(cEntry)
if cValue != nil {
entry.Value = C.GoString(cValue)
}
entry.Source = ConfigSource(C.rd_kafka_ConfigEntry_source(cEntry))
entry.IsReadOnly = cint2bool(C.rd_kafka_ConfigEntry_is_read_only(cEntry))
entry.IsSensitive = cint2bool(C.rd_kafka_ConfigEntry_is_sensitive(cEntry))
entry.IsSynonym = cint2bool(C.rd_kafka_ConfigEntry_is_synonym(cEntry))
var cSynCnt C.size_t
cSyns := C.rd_kafka_ConfigEntry_synonyms(cEntry, &cSynCnt)
if cSynCnt > 0 {
entry.Synonyms = make(map[string]ConfigEntryResult)
}
for si := 0; si < int(cSynCnt); si++ {
cSyn := C.ConfigEntry_by_idx(cSyns, cSynCnt, C.size_t(si))
Syn := configEntryResultFromC(cSyn)
entry.Synonyms[Syn.Name] = Syn
}
return entry
} | go | func configEntryResultFromC(cEntry *C.rd_kafka_ConfigEntry_t) (entry ConfigEntryResult) {
entry.Name = C.GoString(C.rd_kafka_ConfigEntry_name(cEntry))
cValue := C.rd_kafka_ConfigEntry_value(cEntry)
if cValue != nil {
entry.Value = C.GoString(cValue)
}
entry.Source = ConfigSource(C.rd_kafka_ConfigEntry_source(cEntry))
entry.IsReadOnly = cint2bool(C.rd_kafka_ConfigEntry_is_read_only(cEntry))
entry.IsSensitive = cint2bool(C.rd_kafka_ConfigEntry_is_sensitive(cEntry))
entry.IsSynonym = cint2bool(C.rd_kafka_ConfigEntry_is_synonym(cEntry))
var cSynCnt C.size_t
cSyns := C.rd_kafka_ConfigEntry_synonyms(cEntry, &cSynCnt)
if cSynCnt > 0 {
entry.Synonyms = make(map[string]ConfigEntryResult)
}
for si := 0; si < int(cSynCnt); si++ {
cSyn := C.ConfigEntry_by_idx(cSyns, cSynCnt, C.size_t(si))
Syn := configEntryResultFromC(cSyn)
entry.Synonyms[Syn.Name] = Syn
}
return entry
} | [
"func",
"configEntryResultFromC",
"(",
"cEntry",
"*",
"C",
".",
"rd_kafka_ConfigEntry_t",
")",
"(",
"entry",
"ConfigEntryResult",
")",
"{",
"entry",
".",
"Name",
"=",
"C",
".",
"GoString",
"(",
"C",
".",
"rd_kafka_ConfigEntry_name",
"(",
"cEntry",
")",
")",
"\n",
"cValue",
":=",
"C",
".",
"rd_kafka_ConfigEntry_value",
"(",
"cEntry",
")",
"\n",
"if",
"cValue",
"!=",
"nil",
"{",
"entry",
".",
"Value",
"=",
"C",
".",
"GoString",
"(",
"cValue",
")",
"\n",
"}",
"\n",
"entry",
".",
"Source",
"=",
"ConfigSource",
"(",
"C",
".",
"rd_kafka_ConfigEntry_source",
"(",
"cEntry",
")",
")",
"\n",
"entry",
".",
"IsReadOnly",
"=",
"cint2bool",
"(",
"C",
".",
"rd_kafka_ConfigEntry_is_read_only",
"(",
"cEntry",
")",
")",
"\n",
"entry",
".",
"IsSensitive",
"=",
"cint2bool",
"(",
"C",
".",
"rd_kafka_ConfigEntry_is_sensitive",
"(",
"cEntry",
")",
")",
"\n",
"entry",
".",
"IsSynonym",
"=",
"cint2bool",
"(",
"C",
".",
"rd_kafka_ConfigEntry_is_synonym",
"(",
"cEntry",
")",
")",
"\n\n",
"var",
"cSynCnt",
"C",
".",
"size_t",
"\n",
"cSyns",
":=",
"C",
".",
"rd_kafka_ConfigEntry_synonyms",
"(",
"cEntry",
",",
"&",
"cSynCnt",
")",
"\n",
"if",
"cSynCnt",
">",
"0",
"{",
"entry",
".",
"Synonyms",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"ConfigEntryResult",
")",
"\n",
"}",
"\n\n",
"for",
"si",
":=",
"0",
";",
"si",
"<",
"int",
"(",
"cSynCnt",
")",
";",
"si",
"++",
"{",
"cSyn",
":=",
"C",
".",
"ConfigEntry_by_idx",
"(",
"cSyns",
",",
"cSynCnt",
",",
"C",
".",
"size_t",
"(",
"si",
")",
")",
"\n",
"Syn",
":=",
"configEntryResultFromC",
"(",
"cSyn",
")",
"\n",
"entry",
".",
"Synonyms",
"[",
"Syn",
".",
"Name",
"]",
"=",
"Syn",
"\n",
"}",
"\n\n",
"return",
"entry",
"\n",
"}"
] | // setFromC sets up a ConfigEntryResult from a C ConfigEntry | [
"setFromC",
"sets",
"up",
"a",
"ConfigEntryResult",
"from",
"a",
"C",
"ConfigEntry"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L267-L291 |
164,020 | confluentinc/confluent-kafka-go | kafka/adminapi.go | String | func (c ConfigResourceResult) String() string {
if c.Error.Code() != 0 {
return fmt.Sprintf("ResourceResult(%s, %s, \"%v\")", c.Type, c.Name, c.Error)
}
return fmt.Sprintf("ResourceResult(%s, %s, %d config(s))", c.Type, c.Name, len(c.Config))
} | go | func (c ConfigResourceResult) String() string {
if c.Error.Code() != 0 {
return fmt.Sprintf("ResourceResult(%s, %s, \"%v\")", c.Type, c.Name, c.Error)
}
return fmt.Sprintf("ResourceResult(%s, %s, %d config(s))", c.Type, c.Name, len(c.Config))
} | [
"func",
"(",
"c",
"ConfigResourceResult",
")",
"String",
"(",
")",
"string",
"{",
"if",
"c",
".",
"Error",
".",
"Code",
"(",
")",
"!=",
"0",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"c",
".",
"Type",
",",
"c",
".",
"Name",
",",
"c",
".",
"Error",
")",
"\n\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"Type",
",",
"c",
".",
"Name",
",",
"len",
"(",
"c",
".",
"Config",
")",
")",
"\n",
"}"
] | // String returns a human-readable representation of a ConfigResourceResult. | [
"String",
"returns",
"a",
"human",
"-",
"readable",
"representation",
"of",
"a",
"ConfigResourceResult",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L307-L313 |
164,021 | confluentinc/confluent-kafka-go | kafka/adminapi.go | waitResult | func (a *AdminClient) waitResult(ctx context.Context, cQueue *C.rd_kafka_queue_t, cEventType C.rd_kafka_event_type_t) (rkev *C.rd_kafka_event_t, err error) {
resultChan := make(chan *C.rd_kafka_event_t)
closeChan := make(chan bool) // never written to, just closed
go func() {
for {
select {
case _, ok := <-closeChan:
if !ok {
// Context cancelled/timed out
close(resultChan)
return
}
default:
// Wait for result event for at most 50ms
// to avoid blocking for too long if
// context is cancelled.
rkev := C.rd_kafka_queue_poll(cQueue, 50)
if rkev != nil {
resultChan <- rkev
close(resultChan)
return
}
}
}
}()
select {
case rkev = <-resultChan:
// Result type check
if cEventType != C.rd_kafka_event_type(rkev) {
err = newErrorFromString(ErrInvalidType,
fmt.Sprintf("Expected %d result event, not %d", (int)(cEventType), (int)(C.rd_kafka_event_type(rkev))))
C.rd_kafka_event_destroy(rkev)
return nil, err
}
// Generic error handling
cErr := C.rd_kafka_event_error(rkev)
if cErr != 0 {
err = newErrorFromCString(cErr, C.rd_kafka_event_error_string(rkev))
C.rd_kafka_event_destroy(rkev)
return nil, err
}
close(closeChan)
return rkev, nil
case <-ctx.Done():
// signal close to go-routine
close(closeChan)
// wait for close from go-routine to make sure it is done
// using cQueue before we return.
rkev, ok := <-resultChan
if ok {
// throw away result since context was cancelled
C.rd_kafka_event_destroy(rkev)
}
return nil, ctx.Err()
}
} | go | func (a *AdminClient) waitResult(ctx context.Context, cQueue *C.rd_kafka_queue_t, cEventType C.rd_kafka_event_type_t) (rkev *C.rd_kafka_event_t, err error) {
resultChan := make(chan *C.rd_kafka_event_t)
closeChan := make(chan bool) // never written to, just closed
go func() {
for {
select {
case _, ok := <-closeChan:
if !ok {
// Context cancelled/timed out
close(resultChan)
return
}
default:
// Wait for result event for at most 50ms
// to avoid blocking for too long if
// context is cancelled.
rkev := C.rd_kafka_queue_poll(cQueue, 50)
if rkev != nil {
resultChan <- rkev
close(resultChan)
return
}
}
}
}()
select {
case rkev = <-resultChan:
// Result type check
if cEventType != C.rd_kafka_event_type(rkev) {
err = newErrorFromString(ErrInvalidType,
fmt.Sprintf("Expected %d result event, not %d", (int)(cEventType), (int)(C.rd_kafka_event_type(rkev))))
C.rd_kafka_event_destroy(rkev)
return nil, err
}
// Generic error handling
cErr := C.rd_kafka_event_error(rkev)
if cErr != 0 {
err = newErrorFromCString(cErr, C.rd_kafka_event_error_string(rkev))
C.rd_kafka_event_destroy(rkev)
return nil, err
}
close(closeChan)
return rkev, nil
case <-ctx.Done():
// signal close to go-routine
close(closeChan)
// wait for close from go-routine to make sure it is done
// using cQueue before we return.
rkev, ok := <-resultChan
if ok {
// throw away result since context was cancelled
C.rd_kafka_event_destroy(rkev)
}
return nil, ctx.Err()
}
} | [
"func",
"(",
"a",
"*",
"AdminClient",
")",
"waitResult",
"(",
"ctx",
"context",
".",
"Context",
",",
"cQueue",
"*",
"C",
".",
"rd_kafka_queue_t",
",",
"cEventType",
"C",
".",
"rd_kafka_event_type_t",
")",
"(",
"rkev",
"*",
"C",
".",
"rd_kafka_event_t",
",",
"err",
"error",
")",
"{",
"resultChan",
":=",
"make",
"(",
"chan",
"*",
"C",
".",
"rd_kafka_event_t",
")",
"\n",
"closeChan",
":=",
"make",
"(",
"chan",
"bool",
")",
"// never written to, just closed",
"\n\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"_",
",",
"ok",
":=",
"<-",
"closeChan",
":",
"if",
"!",
"ok",
"{",
"// Context cancelled/timed out",
"close",
"(",
"resultChan",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"default",
":",
"// Wait for result event for at most 50ms",
"// to avoid blocking for too long if",
"// context is cancelled.",
"rkev",
":=",
"C",
".",
"rd_kafka_queue_poll",
"(",
"cQueue",
",",
"50",
")",
"\n",
"if",
"rkev",
"!=",
"nil",
"{",
"resultChan",
"<-",
"rkev",
"\n",
"close",
"(",
"resultChan",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"select",
"{",
"case",
"rkev",
"=",
"<-",
"resultChan",
":",
"// Result type check",
"if",
"cEventType",
"!=",
"C",
".",
"rd_kafka_event_type",
"(",
"rkev",
")",
"{",
"err",
"=",
"newErrorFromString",
"(",
"ErrInvalidType",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"(",
"int",
")",
"(",
"cEventType",
")",
",",
"(",
"int",
")",
"(",
"C",
".",
"rd_kafka_event_type",
"(",
"rkev",
")",
")",
")",
")",
"\n",
"C",
".",
"rd_kafka_event_destroy",
"(",
"rkev",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Generic error handling",
"cErr",
":=",
"C",
".",
"rd_kafka_event_error",
"(",
"rkev",
")",
"\n",
"if",
"cErr",
"!=",
"0",
"{",
"err",
"=",
"newErrorFromCString",
"(",
"cErr",
",",
"C",
".",
"rd_kafka_event_error_string",
"(",
"rkev",
")",
")",
"\n",
"C",
".",
"rd_kafka_event_destroy",
"(",
"rkev",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"close",
"(",
"closeChan",
")",
"\n",
"return",
"rkev",
",",
"nil",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"// signal close to go-routine",
"close",
"(",
"closeChan",
")",
"\n",
"// wait for close from go-routine to make sure it is done",
"// using cQueue before we return.",
"rkev",
",",
"ok",
":=",
"<-",
"resultChan",
"\n",
"if",
"ok",
"{",
"// throw away result since context was cancelled",
"C",
".",
"rd_kafka_event_destroy",
"(",
"rkev",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // waitResult waits for a result event on cQueue or the ctx to be cancelled, whichever happens
// first.
// The returned result event is checked for errors its error is returned if set. | [
"waitResult",
"waits",
"for",
"a",
"result",
"event",
"on",
"cQueue",
"or",
"the",
"ctx",
"to",
"be",
"cancelled",
"whichever",
"happens",
"first",
".",
"The",
"returned",
"result",
"event",
"is",
"checked",
"for",
"errors",
"its",
"error",
"is",
"returned",
"if",
"set",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L318-L378 |
164,022 | confluentinc/confluent-kafka-go | kafka/adminapi.go | cToTopicResults | func (a *AdminClient) cToTopicResults(cTopicRes **C.rd_kafka_topic_result_t, cCnt C.size_t) (result []TopicResult, err error) {
result = make([]TopicResult, int(cCnt))
for i := 0; i < int(cCnt); i++ {
cTopic := C.topic_result_by_idx(cTopicRes, cCnt, C.size_t(i))
result[i].Topic = C.GoString(C.rd_kafka_topic_result_name(cTopic))
result[i].Error = newErrorFromCString(
C.rd_kafka_topic_result_error(cTopic),
C.rd_kafka_topic_result_error_string(cTopic))
}
return result, nil
} | go | func (a *AdminClient) cToTopicResults(cTopicRes **C.rd_kafka_topic_result_t, cCnt C.size_t) (result []TopicResult, err error) {
result = make([]TopicResult, int(cCnt))
for i := 0; i < int(cCnt); i++ {
cTopic := C.topic_result_by_idx(cTopicRes, cCnt, C.size_t(i))
result[i].Topic = C.GoString(C.rd_kafka_topic_result_name(cTopic))
result[i].Error = newErrorFromCString(
C.rd_kafka_topic_result_error(cTopic),
C.rd_kafka_topic_result_error_string(cTopic))
}
return result, nil
} | [
"func",
"(",
"a",
"*",
"AdminClient",
")",
"cToTopicResults",
"(",
"cTopicRes",
"*",
"*",
"C",
".",
"rd_kafka_topic_result_t",
",",
"cCnt",
"C",
".",
"size_t",
")",
"(",
"result",
"[",
"]",
"TopicResult",
",",
"err",
"error",
")",
"{",
"result",
"=",
"make",
"(",
"[",
"]",
"TopicResult",
",",
"int",
"(",
"cCnt",
")",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"int",
"(",
"cCnt",
")",
";",
"i",
"++",
"{",
"cTopic",
":=",
"C",
".",
"topic_result_by_idx",
"(",
"cTopicRes",
",",
"cCnt",
",",
"C",
".",
"size_t",
"(",
"i",
")",
")",
"\n",
"result",
"[",
"i",
"]",
".",
"Topic",
"=",
"C",
".",
"GoString",
"(",
"C",
".",
"rd_kafka_topic_result_name",
"(",
"cTopic",
")",
")",
"\n",
"result",
"[",
"i",
"]",
".",
"Error",
"=",
"newErrorFromCString",
"(",
"C",
".",
"rd_kafka_topic_result_error",
"(",
"cTopic",
")",
",",
"C",
".",
"rd_kafka_topic_result_error_string",
"(",
"cTopic",
")",
")",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // cToTopicResults converts a C topic_result_t array to Go TopicResult list. | [
"cToTopicResults",
"converts",
"a",
"C",
"topic_result_t",
"array",
"to",
"Go",
"TopicResult",
"list",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L381-L394 |
164,023 | confluentinc/confluent-kafka-go | kafka/adminapi.go | cConfigResourceToResult | func (a *AdminClient) cConfigResourceToResult(cRes **C.rd_kafka_ConfigResource_t, cCnt C.size_t) (result []ConfigResourceResult, err error) {
result = make([]ConfigResourceResult, int(cCnt))
for i := 0; i < int(cCnt); i++ {
cRes := C.ConfigResource_by_idx(cRes, cCnt, C.size_t(i))
result[i].Type = ResourceType(C.rd_kafka_ConfigResource_type(cRes))
result[i].Name = C.GoString(C.rd_kafka_ConfigResource_name(cRes))
result[i].Error = newErrorFromCString(
C.rd_kafka_ConfigResource_error(cRes),
C.rd_kafka_ConfigResource_error_string(cRes))
var cConfigCnt C.size_t
cConfigs := C.rd_kafka_ConfigResource_configs(cRes, &cConfigCnt)
if cConfigCnt > 0 {
result[i].Config = make(map[string]ConfigEntryResult)
}
for ci := 0; ci < int(cConfigCnt); ci++ {
cEntry := C.ConfigEntry_by_idx(cConfigs, cConfigCnt, C.size_t(ci))
entry := configEntryResultFromC(cEntry)
result[i].Config[entry.Name] = entry
}
}
return result, nil
} | go | func (a *AdminClient) cConfigResourceToResult(cRes **C.rd_kafka_ConfigResource_t, cCnt C.size_t) (result []ConfigResourceResult, err error) {
result = make([]ConfigResourceResult, int(cCnt))
for i := 0; i < int(cCnt); i++ {
cRes := C.ConfigResource_by_idx(cRes, cCnt, C.size_t(i))
result[i].Type = ResourceType(C.rd_kafka_ConfigResource_type(cRes))
result[i].Name = C.GoString(C.rd_kafka_ConfigResource_name(cRes))
result[i].Error = newErrorFromCString(
C.rd_kafka_ConfigResource_error(cRes),
C.rd_kafka_ConfigResource_error_string(cRes))
var cConfigCnt C.size_t
cConfigs := C.rd_kafka_ConfigResource_configs(cRes, &cConfigCnt)
if cConfigCnt > 0 {
result[i].Config = make(map[string]ConfigEntryResult)
}
for ci := 0; ci < int(cConfigCnt); ci++ {
cEntry := C.ConfigEntry_by_idx(cConfigs, cConfigCnt, C.size_t(ci))
entry := configEntryResultFromC(cEntry)
result[i].Config[entry.Name] = entry
}
}
return result, nil
} | [
"func",
"(",
"a",
"*",
"AdminClient",
")",
"cConfigResourceToResult",
"(",
"cRes",
"*",
"*",
"C",
".",
"rd_kafka_ConfigResource_t",
",",
"cCnt",
"C",
".",
"size_t",
")",
"(",
"result",
"[",
"]",
"ConfigResourceResult",
",",
"err",
"error",
")",
"{",
"result",
"=",
"make",
"(",
"[",
"]",
"ConfigResourceResult",
",",
"int",
"(",
"cCnt",
")",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"int",
"(",
"cCnt",
")",
";",
"i",
"++",
"{",
"cRes",
":=",
"C",
".",
"ConfigResource_by_idx",
"(",
"cRes",
",",
"cCnt",
",",
"C",
".",
"size_t",
"(",
"i",
")",
")",
"\n",
"result",
"[",
"i",
"]",
".",
"Type",
"=",
"ResourceType",
"(",
"C",
".",
"rd_kafka_ConfigResource_type",
"(",
"cRes",
")",
")",
"\n",
"result",
"[",
"i",
"]",
".",
"Name",
"=",
"C",
".",
"GoString",
"(",
"C",
".",
"rd_kafka_ConfigResource_name",
"(",
"cRes",
")",
")",
"\n",
"result",
"[",
"i",
"]",
".",
"Error",
"=",
"newErrorFromCString",
"(",
"C",
".",
"rd_kafka_ConfigResource_error",
"(",
"cRes",
")",
",",
"C",
".",
"rd_kafka_ConfigResource_error_string",
"(",
"cRes",
")",
")",
"\n",
"var",
"cConfigCnt",
"C",
".",
"size_t",
"\n",
"cConfigs",
":=",
"C",
".",
"rd_kafka_ConfigResource_configs",
"(",
"cRes",
",",
"&",
"cConfigCnt",
")",
"\n",
"if",
"cConfigCnt",
">",
"0",
"{",
"result",
"[",
"i",
"]",
".",
"Config",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"ConfigEntryResult",
")",
"\n",
"}",
"\n",
"for",
"ci",
":=",
"0",
";",
"ci",
"<",
"int",
"(",
"cConfigCnt",
")",
";",
"ci",
"++",
"{",
"cEntry",
":=",
"C",
".",
"ConfigEntry_by_idx",
"(",
"cConfigs",
",",
"cConfigCnt",
",",
"C",
".",
"size_t",
"(",
"ci",
")",
")",
"\n",
"entry",
":=",
"configEntryResultFromC",
"(",
"cEntry",
")",
"\n",
"result",
"[",
"i",
"]",
".",
"Config",
"[",
"entry",
".",
"Name",
"]",
"=",
"entry",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // cConfigResourceToResult converts a C ConfigResource result array to Go ConfigResourceResult | [
"cConfigResourceToResult",
"converts",
"a",
"C",
"ConfigResource",
"result",
"array",
"to",
"Go",
"ConfigResourceResult"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L397-L421 |
164,024 | confluentinc/confluent-kafka-go | kafka/adminapi.go | DeleteTopics | func (a *AdminClient) DeleteTopics(ctx context.Context, topics []string, options ...DeleteTopicsAdminOption) (result []TopicResult, err error) {
cTopics := make([]*C.rd_kafka_DeleteTopic_t, len(topics))
cErrstrSize := C.size_t(512)
cErrstr := (*C.char)(C.malloc(cErrstrSize))
defer C.free(unsafe.Pointer(cErrstr))
// Convert Go DeleteTopics to C DeleteTopics
for i, topic := range topics {
cTopics[i] = C.rd_kafka_DeleteTopic_new(C.CString(topic))
if cTopics[i] == nil {
return nil, newErrorFromString(ErrInvalidArg,
fmt.Sprintf("Invalid arguments for topic %s", topic))
}
defer C.rd_kafka_DeleteTopic_destroy(cTopics[i])
}
// Convert Go AdminOptions (if any) to C AdminOptions
genericOptions := make([]AdminOption, len(options))
for i := range options {
genericOptions[i] = options[i]
}
cOptions, err := adminOptionsSetup(a.handle, C.RD_KAFKA_ADMIN_OP_DELETETOPICS, genericOptions)
if err != nil {
return nil, err
}
defer C.rd_kafka_AdminOptions_destroy(cOptions)
// Create temporary queue for async operation
cQueue := C.rd_kafka_queue_new(a.handle.rk)
defer C.rd_kafka_queue_destroy(cQueue)
// Asynchronous call
C.rd_kafka_DeleteTopics(
a.handle.rk,
(**C.rd_kafka_DeleteTopic_t)(&cTopics[0]),
C.size_t(len(cTopics)),
cOptions,
cQueue)
// Wait for result, error or context timeout
rkev, err := a.waitResult(ctx, cQueue, C.RD_KAFKA_EVENT_DELETETOPICS_RESULT)
if err != nil {
return nil, err
}
defer C.rd_kafka_event_destroy(rkev)
cRes := C.rd_kafka_event_DeleteTopics_result(rkev)
// Convert result from C to Go
var cCnt C.size_t
cTopicRes := C.rd_kafka_DeleteTopics_result_topics(cRes, &cCnt)
return a.cToTopicResults(cTopicRes, cCnt)
} | go | func (a *AdminClient) DeleteTopics(ctx context.Context, topics []string, options ...DeleteTopicsAdminOption) (result []TopicResult, err error) {
cTopics := make([]*C.rd_kafka_DeleteTopic_t, len(topics))
cErrstrSize := C.size_t(512)
cErrstr := (*C.char)(C.malloc(cErrstrSize))
defer C.free(unsafe.Pointer(cErrstr))
// Convert Go DeleteTopics to C DeleteTopics
for i, topic := range topics {
cTopics[i] = C.rd_kafka_DeleteTopic_new(C.CString(topic))
if cTopics[i] == nil {
return nil, newErrorFromString(ErrInvalidArg,
fmt.Sprintf("Invalid arguments for topic %s", topic))
}
defer C.rd_kafka_DeleteTopic_destroy(cTopics[i])
}
// Convert Go AdminOptions (if any) to C AdminOptions
genericOptions := make([]AdminOption, len(options))
for i := range options {
genericOptions[i] = options[i]
}
cOptions, err := adminOptionsSetup(a.handle, C.RD_KAFKA_ADMIN_OP_DELETETOPICS, genericOptions)
if err != nil {
return nil, err
}
defer C.rd_kafka_AdminOptions_destroy(cOptions)
// Create temporary queue for async operation
cQueue := C.rd_kafka_queue_new(a.handle.rk)
defer C.rd_kafka_queue_destroy(cQueue)
// Asynchronous call
C.rd_kafka_DeleteTopics(
a.handle.rk,
(**C.rd_kafka_DeleteTopic_t)(&cTopics[0]),
C.size_t(len(cTopics)),
cOptions,
cQueue)
// Wait for result, error or context timeout
rkev, err := a.waitResult(ctx, cQueue, C.RD_KAFKA_EVENT_DELETETOPICS_RESULT)
if err != nil {
return nil, err
}
defer C.rd_kafka_event_destroy(rkev)
cRes := C.rd_kafka_event_DeleteTopics_result(rkev)
// Convert result from C to Go
var cCnt C.size_t
cTopicRes := C.rd_kafka_DeleteTopics_result_topics(cRes, &cCnt)
return a.cToTopicResults(cTopicRes, cCnt)
} | [
"func",
"(",
"a",
"*",
"AdminClient",
")",
"DeleteTopics",
"(",
"ctx",
"context",
".",
"Context",
",",
"topics",
"[",
"]",
"string",
",",
"options",
"...",
"DeleteTopicsAdminOption",
")",
"(",
"result",
"[",
"]",
"TopicResult",
",",
"err",
"error",
")",
"{",
"cTopics",
":=",
"make",
"(",
"[",
"]",
"*",
"C",
".",
"rd_kafka_DeleteTopic_t",
",",
"len",
"(",
"topics",
")",
")",
"\n\n",
"cErrstrSize",
":=",
"C",
".",
"size_t",
"(",
"512",
")",
"\n",
"cErrstr",
":=",
"(",
"*",
"C",
".",
"char",
")",
"(",
"C",
".",
"malloc",
"(",
"cErrstrSize",
")",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cErrstr",
")",
")",
"\n\n",
"// Convert Go DeleteTopics to C DeleteTopics",
"for",
"i",
",",
"topic",
":=",
"range",
"topics",
"{",
"cTopics",
"[",
"i",
"]",
"=",
"C",
".",
"rd_kafka_DeleteTopic_new",
"(",
"C",
".",
"CString",
"(",
"topic",
")",
")",
"\n",
"if",
"cTopics",
"[",
"i",
"]",
"==",
"nil",
"{",
"return",
"nil",
",",
"newErrorFromString",
"(",
"ErrInvalidArg",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"topic",
")",
")",
"\n",
"}",
"\n\n",
"defer",
"C",
".",
"rd_kafka_DeleteTopic_destroy",
"(",
"cTopics",
"[",
"i",
"]",
")",
"\n",
"}",
"\n\n",
"// Convert Go AdminOptions (if any) to C AdminOptions",
"genericOptions",
":=",
"make",
"(",
"[",
"]",
"AdminOption",
",",
"len",
"(",
"options",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"options",
"{",
"genericOptions",
"[",
"i",
"]",
"=",
"options",
"[",
"i",
"]",
"\n",
"}",
"\n",
"cOptions",
",",
"err",
":=",
"adminOptionsSetup",
"(",
"a",
".",
"handle",
",",
"C",
".",
"RD_KAFKA_ADMIN_OP_DELETETOPICS",
",",
"genericOptions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"C",
".",
"rd_kafka_AdminOptions_destroy",
"(",
"cOptions",
")",
"\n\n",
"// Create temporary queue for async operation",
"cQueue",
":=",
"C",
".",
"rd_kafka_queue_new",
"(",
"a",
".",
"handle",
".",
"rk",
")",
"\n",
"defer",
"C",
".",
"rd_kafka_queue_destroy",
"(",
"cQueue",
")",
"\n\n",
"// Asynchronous call",
"C",
".",
"rd_kafka_DeleteTopics",
"(",
"a",
".",
"handle",
".",
"rk",
",",
"(",
"*",
"*",
"C",
".",
"rd_kafka_DeleteTopic_t",
")",
"(",
"&",
"cTopics",
"[",
"0",
"]",
")",
",",
"C",
".",
"size_t",
"(",
"len",
"(",
"cTopics",
")",
")",
",",
"cOptions",
",",
"cQueue",
")",
"\n\n",
"// Wait for result, error or context timeout",
"rkev",
",",
"err",
":=",
"a",
".",
"waitResult",
"(",
"ctx",
",",
"cQueue",
",",
"C",
".",
"RD_KAFKA_EVENT_DELETETOPICS_RESULT",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"C",
".",
"rd_kafka_event_destroy",
"(",
"rkev",
")",
"\n\n",
"cRes",
":=",
"C",
".",
"rd_kafka_event_DeleteTopics_result",
"(",
"rkev",
")",
"\n\n",
"// Convert result from C to Go",
"var",
"cCnt",
"C",
".",
"size_t",
"\n",
"cTopicRes",
":=",
"C",
".",
"rd_kafka_DeleteTopics_result_topics",
"(",
"cRes",
",",
"&",
"cCnt",
")",
"\n\n",
"return",
"a",
".",
"cToTopicResults",
"(",
"cTopicRes",
",",
"cCnt",
")",
"\n",
"}"
] | // DeleteTopics deletes a batch of topics.
//
// This operation is not transactional and may succeed for a subset of topics while
// failing others.
// It may take several seconds after the DeleteTopics result returns success for
// all the brokers to become aware that the topics are gone. During this time,
// topic metadata and configuration may continue to return information about deleted topics.
//
// Requires broker version >= 0.10.1.0 | [
"DeleteTopics",
"deletes",
"a",
"batch",
"of",
"topics",
".",
"This",
"operation",
"is",
"not",
"transactional",
"and",
"may",
"succeed",
"for",
"a",
"subset",
"of",
"topics",
"while",
"failing",
"others",
".",
"It",
"may",
"take",
"several",
"seconds",
"after",
"the",
"DeleteTopics",
"result",
"returns",
"success",
"for",
"all",
"the",
"brokers",
"to",
"become",
"aware",
"that",
"the",
"topics",
"are",
"gone",
".",
"During",
"this",
"time",
"topic",
"metadata",
"and",
"configuration",
"may",
"continue",
"to",
"return",
"information",
"about",
"deleted",
"topics",
".",
"Requires",
"broker",
"version",
">",
"=",
"0",
".",
"10",
".",
"1",
".",
"0"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L549-L604 |
164,025 | confluentinc/confluent-kafka-go | kafka/adminapi.go | Close | func (a *AdminClient) Close() {
if a.isDerived {
// Derived AdminClient needs no cleanup.
a.handle = &handle{}
return
}
a.handle.cleanup()
C.rd_kafka_destroy(a.handle.rk)
} | go | func (a *AdminClient) Close() {
if a.isDerived {
// Derived AdminClient needs no cleanup.
a.handle = &handle{}
return
}
a.handle.cleanup()
C.rd_kafka_destroy(a.handle.rk)
} | [
"func",
"(",
"a",
"*",
"AdminClient",
")",
"Close",
"(",
")",
"{",
"if",
"a",
".",
"isDerived",
"{",
"// Derived AdminClient needs no cleanup.",
"a",
".",
"handle",
"=",
"&",
"handle",
"{",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"a",
".",
"handle",
".",
"cleanup",
"(",
")",
"\n\n",
"C",
".",
"rd_kafka_destroy",
"(",
"a",
".",
"handle",
".",
"rk",
")",
"\n",
"}"
] | // Close an AdminClient instance. | [
"Close",
"an",
"AdminClient",
"instance",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L873-L883 |
164,026 | confluentinc/confluent-kafka-go | kafka/adminapi.go | NewAdminClient | func NewAdminClient(conf *ConfigMap) (*AdminClient, error) {
err := versionCheck()
if err != nil {
return nil, err
}
a := &AdminClient{}
a.handle = &handle{}
// Convert ConfigMap to librdkafka conf_t
cConf, err := conf.convert()
if err != nil {
return nil, err
}
cErrstr := (*C.char)(C.malloc(C.size_t(256)))
defer C.free(unsafe.Pointer(cErrstr))
// Create librdkafka producer instance. The Producer is somewhat cheaper than
// the consumer, but any instance type can be used for Admin APIs.
a.handle.rk = C.rd_kafka_new(C.RD_KAFKA_PRODUCER, cConf, cErrstr, 256)
if a.handle.rk == nil {
return nil, newErrorFromCString(C.RD_KAFKA_RESP_ERR__INVALID_ARG, cErrstr)
}
a.isDerived = false
a.handle.setup()
return a, nil
} | go | func NewAdminClient(conf *ConfigMap) (*AdminClient, error) {
err := versionCheck()
if err != nil {
return nil, err
}
a := &AdminClient{}
a.handle = &handle{}
// Convert ConfigMap to librdkafka conf_t
cConf, err := conf.convert()
if err != nil {
return nil, err
}
cErrstr := (*C.char)(C.malloc(C.size_t(256)))
defer C.free(unsafe.Pointer(cErrstr))
// Create librdkafka producer instance. The Producer is somewhat cheaper than
// the consumer, but any instance type can be used for Admin APIs.
a.handle.rk = C.rd_kafka_new(C.RD_KAFKA_PRODUCER, cConf, cErrstr, 256)
if a.handle.rk == nil {
return nil, newErrorFromCString(C.RD_KAFKA_RESP_ERR__INVALID_ARG, cErrstr)
}
a.isDerived = false
a.handle.setup()
return a, nil
} | [
"func",
"NewAdminClient",
"(",
"conf",
"*",
"ConfigMap",
")",
"(",
"*",
"AdminClient",
",",
"error",
")",
"{",
"err",
":=",
"versionCheck",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"a",
":=",
"&",
"AdminClient",
"{",
"}",
"\n",
"a",
".",
"handle",
"=",
"&",
"handle",
"{",
"}",
"\n\n",
"// Convert ConfigMap to librdkafka conf_t",
"cConf",
",",
"err",
":=",
"conf",
".",
"convert",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"cErrstr",
":=",
"(",
"*",
"C",
".",
"char",
")",
"(",
"C",
".",
"malloc",
"(",
"C",
".",
"size_t",
"(",
"256",
")",
")",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cErrstr",
")",
")",
"\n\n",
"// Create librdkafka producer instance. The Producer is somewhat cheaper than",
"// the consumer, but any instance type can be used for Admin APIs.",
"a",
".",
"handle",
".",
"rk",
"=",
"C",
".",
"rd_kafka_new",
"(",
"C",
".",
"RD_KAFKA_PRODUCER",
",",
"cConf",
",",
"cErrstr",
",",
"256",
")",
"\n",
"if",
"a",
".",
"handle",
".",
"rk",
"==",
"nil",
"{",
"return",
"nil",
",",
"newErrorFromCString",
"(",
"C",
".",
"RD_KAFKA_RESP_ERR__INVALID_ARG",
",",
"cErrstr",
")",
"\n",
"}",
"\n\n",
"a",
".",
"isDerived",
"=",
"false",
"\n",
"a",
".",
"handle",
".",
"setup",
"(",
")",
"\n\n",
"return",
"a",
",",
"nil",
"\n",
"}"
] | // NewAdminClient creats a new AdminClient instance with a new underlying client instance | [
"NewAdminClient",
"creats",
"a",
"new",
"AdminClient",
"instance",
"with",
"a",
"new",
"underlying",
"client",
"instance"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L886-L916 |
164,027 | confluentinc/confluent-kafka-go | kafka/adminapi.go | NewAdminClientFromProducer | func NewAdminClientFromProducer(p *Producer) (a *AdminClient, err error) {
if p.handle.rk == nil {
return nil, newErrorFromString(ErrInvalidArg, "Can't derive AdminClient from closed producer")
}
a = &AdminClient{}
a.handle = &p.handle
a.isDerived = true
return a, nil
} | go | func NewAdminClientFromProducer(p *Producer) (a *AdminClient, err error) {
if p.handle.rk == nil {
return nil, newErrorFromString(ErrInvalidArg, "Can't derive AdminClient from closed producer")
}
a = &AdminClient{}
a.handle = &p.handle
a.isDerived = true
return a, nil
} | [
"func",
"NewAdminClientFromProducer",
"(",
"p",
"*",
"Producer",
")",
"(",
"a",
"*",
"AdminClient",
",",
"err",
"error",
")",
"{",
"if",
"p",
".",
"handle",
".",
"rk",
"==",
"nil",
"{",
"return",
"nil",
",",
"newErrorFromString",
"(",
"ErrInvalidArg",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"a",
"=",
"&",
"AdminClient",
"{",
"}",
"\n",
"a",
".",
"handle",
"=",
"&",
"p",
".",
"handle",
"\n",
"a",
".",
"isDerived",
"=",
"true",
"\n",
"return",
"a",
",",
"nil",
"\n",
"}"
] | // NewAdminClientFromProducer derives a new AdminClient from an existing Producer instance.
// The AdminClient will use the same configuration and connections as the parent instance. | [
"NewAdminClientFromProducer",
"derives",
"a",
"new",
"AdminClient",
"from",
"an",
"existing",
"Producer",
"instance",
".",
"The",
"AdminClient",
"will",
"use",
"the",
"same",
"configuration",
"and",
"connections",
"as",
"the",
"parent",
"instance",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L920-L929 |
164,028 | confluentinc/confluent-kafka-go | kafka/adminapi.go | NewAdminClientFromConsumer | func NewAdminClientFromConsumer(c *Consumer) (a *AdminClient, err error) {
if c.handle.rk == nil {
return nil, newErrorFromString(ErrInvalidArg, "Can't derive AdminClient from closed consumer")
}
a = &AdminClient{}
a.handle = &c.handle
a.isDerived = true
return a, nil
} | go | func NewAdminClientFromConsumer(c *Consumer) (a *AdminClient, err error) {
if c.handle.rk == nil {
return nil, newErrorFromString(ErrInvalidArg, "Can't derive AdminClient from closed consumer")
}
a = &AdminClient{}
a.handle = &c.handle
a.isDerived = true
return a, nil
} | [
"func",
"NewAdminClientFromConsumer",
"(",
"c",
"*",
"Consumer",
")",
"(",
"a",
"*",
"AdminClient",
",",
"err",
"error",
")",
"{",
"if",
"c",
".",
"handle",
".",
"rk",
"==",
"nil",
"{",
"return",
"nil",
",",
"newErrorFromString",
"(",
"ErrInvalidArg",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"a",
"=",
"&",
"AdminClient",
"{",
"}",
"\n",
"a",
".",
"handle",
"=",
"&",
"c",
".",
"handle",
"\n",
"a",
".",
"isDerived",
"=",
"true",
"\n",
"return",
"a",
",",
"nil",
"\n",
"}"
] | // NewAdminClientFromConsumer derives a new AdminClient from an existing Consumer instance.
// The AdminClient will use the same configuration and connections as the parent instance. | [
"NewAdminClientFromConsumer",
"derives",
"a",
"new",
"AdminClient",
"from",
"an",
"existing",
"Consumer",
"instance",
".",
"The",
"AdminClient",
"will",
"use",
"the",
"same",
"configuration",
"and",
"connections",
"as",
"the",
"parent",
"instance",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/adminapi.go#L933-L942 |
164,029 | confluentinc/confluent-kafka-go | kafka/config.go | get | func (m ConfigMap) get(key string, defval ConfigValue) (ConfigValue, error) {
if strings.HasPrefix(key, "{topic}.") {
defconfCv, found := m["default.topic.config"]
if !found {
return defval, nil
}
return defconfCv.(ConfigMap).get(strings.TrimPrefix(key, "{topic}."), defval)
}
v, ok := m[key]
if !ok {
return defval, nil
}
if defval != nil && reflect.TypeOf(defval) != reflect.TypeOf(v) {
return nil, newErrorFromString(ErrInvalidArg, fmt.Sprintf("%s expects type %T, not %T", key, defval, v))
}
return v, nil
} | go | func (m ConfigMap) get(key string, defval ConfigValue) (ConfigValue, error) {
if strings.HasPrefix(key, "{topic}.") {
defconfCv, found := m["default.topic.config"]
if !found {
return defval, nil
}
return defconfCv.(ConfigMap).get(strings.TrimPrefix(key, "{topic}."), defval)
}
v, ok := m[key]
if !ok {
return defval, nil
}
if defval != nil && reflect.TypeOf(defval) != reflect.TypeOf(v) {
return nil, newErrorFromString(ErrInvalidArg, fmt.Sprintf("%s expects type %T, not %T", key, defval, v))
}
return v, nil
} | [
"func",
"(",
"m",
"ConfigMap",
")",
"get",
"(",
"key",
"string",
",",
"defval",
"ConfigValue",
")",
"(",
"ConfigValue",
",",
"error",
")",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"\"",
"\"",
")",
"{",
"defconfCv",
",",
"found",
":=",
"m",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"defval",
",",
"nil",
"\n",
"}",
"\n",
"return",
"defconfCv",
".",
"(",
"ConfigMap",
")",
".",
"get",
"(",
"strings",
".",
"TrimPrefix",
"(",
"key",
",",
"\"",
"\"",
")",
",",
"defval",
")",
"\n",
"}",
"\n\n",
"v",
",",
"ok",
":=",
"m",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"defval",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"defval",
"!=",
"nil",
"&&",
"reflect",
".",
"TypeOf",
"(",
"defval",
")",
"!=",
"reflect",
".",
"TypeOf",
"(",
"v",
")",
"{",
"return",
"nil",
",",
"newErrorFromString",
"(",
"ErrInvalidArg",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"key",
",",
"defval",
",",
"v",
")",
")",
"\n",
"}",
"\n\n",
"return",
"v",
",",
"nil",
"\n",
"}"
] | // get finds key in the configmap and returns its value.
// If the key is not found defval is returned.
// If the key is found but the type is mismatched an error is returned. | [
"get",
"finds",
"key",
"in",
"the",
"configmap",
"and",
"returns",
"its",
"value",
".",
"If",
"the",
"key",
"is",
"not",
"found",
"defval",
"is",
"returned",
".",
"If",
"the",
"key",
"is",
"found",
"but",
"the",
"type",
"is",
"mismatched",
"an",
"error",
"is",
"returned",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/config.go#L201-L220 |
164,030 | confluentinc/confluent-kafka-go | kafka/metadata.go | queryWatermarkOffsets | func queryWatermarkOffsets(H Handle, topic string, partition int32, timeoutMs int) (low, high int64, err error) {
h := H.gethandle()
ctopic := C.CString(topic)
defer C.free(unsafe.Pointer(ctopic))
var cLow, cHigh C.int64_t
e := C.rd_kafka_query_watermark_offsets(h.rk, ctopic, C.int32_t(partition),
&cLow, &cHigh, C.int(timeoutMs))
if e != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return 0, 0, newError(e)
}
low = int64(cLow)
high = int64(cHigh)
return low, high, nil
} | go | func queryWatermarkOffsets(H Handle, topic string, partition int32, timeoutMs int) (low, high int64, err error) {
h := H.gethandle()
ctopic := C.CString(topic)
defer C.free(unsafe.Pointer(ctopic))
var cLow, cHigh C.int64_t
e := C.rd_kafka_query_watermark_offsets(h.rk, ctopic, C.int32_t(partition),
&cLow, &cHigh, C.int(timeoutMs))
if e != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return 0, 0, newError(e)
}
low = int64(cLow)
high = int64(cHigh)
return low, high, nil
} | [
"func",
"queryWatermarkOffsets",
"(",
"H",
"Handle",
",",
"topic",
"string",
",",
"partition",
"int32",
",",
"timeoutMs",
"int",
")",
"(",
"low",
",",
"high",
"int64",
",",
"err",
"error",
")",
"{",
"h",
":=",
"H",
".",
"gethandle",
"(",
")",
"\n\n",
"ctopic",
":=",
"C",
".",
"CString",
"(",
"topic",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"ctopic",
")",
")",
"\n\n",
"var",
"cLow",
",",
"cHigh",
"C",
".",
"int64_t",
"\n\n",
"e",
":=",
"C",
".",
"rd_kafka_query_watermark_offsets",
"(",
"h",
".",
"rk",
",",
"ctopic",
",",
"C",
".",
"int32_t",
"(",
"partition",
")",
",",
"&",
"cLow",
",",
"&",
"cHigh",
",",
"C",
".",
"int",
"(",
"timeoutMs",
")",
")",
"\n",
"if",
"e",
"!=",
"C",
".",
"RD_KAFKA_RESP_ERR_NO_ERROR",
"{",
"return",
"0",
",",
"0",
",",
"newError",
"(",
"e",
")",
"\n",
"}",
"\n\n",
"low",
"=",
"int64",
"(",
"cLow",
")",
"\n",
"high",
"=",
"int64",
"(",
"cHigh",
")",
"\n",
"return",
"low",
",",
"high",
",",
"nil",
"\n",
"}"
] | // queryWatermarkOffsets returns the broker's low and high offsets for the given topic
// and partition. | [
"queryWatermarkOffsets",
"returns",
"the",
"broker",
"s",
"low",
"and",
"high",
"offsets",
"for",
"the",
"given",
"topic",
"and",
"partition",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/metadata.go#L141-L158 |
164,031 | confluentinc/confluent-kafka-go | kafka/offset.go | OffsetTail | func OffsetTail(relativeOffset Offset) Offset {
return Offset(C._c_rdkafka_offset_tail(C.int64_t(relativeOffset)))
} | go | func OffsetTail(relativeOffset Offset) Offset {
return Offset(C._c_rdkafka_offset_tail(C.int64_t(relativeOffset)))
} | [
"func",
"OffsetTail",
"(",
"relativeOffset",
"Offset",
")",
"Offset",
"{",
"return",
"Offset",
"(",
"C",
".",
"_c_rdkafka_offset_tail",
"(",
"C",
".",
"int64_t",
"(",
"relativeOffset",
")",
")",
")",
"\n",
"}"
] | // OffsetTail returns the logical offset relativeOffset from current end of partition | [
"OffsetTail",
"returns",
"the",
"logical",
"offset",
"relativeOffset",
"from",
"current",
"end",
"of",
"partition"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/offset.go#L117-L119 |
164,032 | confluentinc/confluent-kafka-go | kafka/offset.go | offsetsForTimes | func offsetsForTimes(H Handle, times []TopicPartition, timeoutMs int) (offsets []TopicPartition, err error) {
cparts := newCPartsFromTopicPartitions(times)
defer C.rd_kafka_topic_partition_list_destroy(cparts)
cerr := C.rd_kafka_offsets_for_times(H.gethandle().rk, cparts, C.int(timeoutMs))
if cerr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newError(cerr)
}
return newTopicPartitionsFromCparts(cparts), nil
} | go | func offsetsForTimes(H Handle, times []TopicPartition, timeoutMs int) (offsets []TopicPartition, err error) {
cparts := newCPartsFromTopicPartitions(times)
defer C.rd_kafka_topic_partition_list_destroy(cparts)
cerr := C.rd_kafka_offsets_for_times(H.gethandle().rk, cparts, C.int(timeoutMs))
if cerr != C.RD_KAFKA_RESP_ERR_NO_ERROR {
return nil, newError(cerr)
}
return newTopicPartitionsFromCparts(cparts), nil
} | [
"func",
"offsetsForTimes",
"(",
"H",
"Handle",
",",
"times",
"[",
"]",
"TopicPartition",
",",
"timeoutMs",
"int",
")",
"(",
"offsets",
"[",
"]",
"TopicPartition",
",",
"err",
"error",
")",
"{",
"cparts",
":=",
"newCPartsFromTopicPartitions",
"(",
"times",
")",
"\n",
"defer",
"C",
".",
"rd_kafka_topic_partition_list_destroy",
"(",
"cparts",
")",
"\n",
"cerr",
":=",
"C",
".",
"rd_kafka_offsets_for_times",
"(",
"H",
".",
"gethandle",
"(",
")",
".",
"rk",
",",
"cparts",
",",
"C",
".",
"int",
"(",
"timeoutMs",
")",
")",
"\n",
"if",
"cerr",
"!=",
"C",
".",
"RD_KAFKA_RESP_ERR_NO_ERROR",
"{",
"return",
"nil",
",",
"newError",
"(",
"cerr",
")",
"\n",
"}",
"\n\n",
"return",
"newTopicPartitionsFromCparts",
"(",
"cparts",
")",
",",
"nil",
"\n",
"}"
] | // offsetsForTimes looks up offsets by timestamp for the given partitions.
//
// The returned offset for each partition is the earliest offset whose
// timestamp is greater than or equal to the given timestamp in the
// corresponding partition.
//
// The timestamps to query are represented as `.Offset` in the `times`
// argument and the looked up offsets are represented as `.Offset` in the returned
// `offsets` list.
//
// The function will block for at most timeoutMs milliseconds.
//
// Duplicate Topic+Partitions are not supported.
// Per-partition errors may be returned in the `.Error` field. | [
"offsetsForTimes",
"looks",
"up",
"offsets",
"by",
"timestamp",
"for",
"the",
"given",
"partitions",
".",
"The",
"returned",
"offset",
"for",
"each",
"partition",
"is",
"the",
"earliest",
"offset",
"whose",
"timestamp",
"is",
"greater",
"than",
"or",
"equal",
"to",
"the",
"given",
"timestamp",
"in",
"the",
"corresponding",
"partition",
".",
"The",
"timestamps",
"to",
"query",
"are",
"represented",
"as",
".",
"Offset",
"in",
"the",
"times",
"argument",
"and",
"the",
"looked",
"up",
"offsets",
"are",
"represented",
"as",
".",
"Offset",
"in",
"the",
"returned",
"offsets",
"list",
".",
"The",
"function",
"will",
"block",
"for",
"at",
"most",
"timeoutMs",
"milliseconds",
".",
"Duplicate",
"Topic",
"+",
"Partitions",
"are",
"not",
"supported",
".",
"Per",
"-",
"partition",
"errors",
"may",
"be",
"returned",
"in",
"the",
".",
"Error",
"field",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/offset.go#L135-L144 |
164,033 | confluentinc/confluent-kafka-go | kafka/producer.go | Len | func (p *Producer) Len() int {
return len(p.produceChannel) + len(p.events) + int(C.rd_kafka_outq_len(p.handle.rk))
} | go | func (p *Producer) Len() int {
return len(p.produceChannel) + len(p.events) + int(C.rd_kafka_outq_len(p.handle.rk))
} | [
"func",
"(",
"p",
"*",
"Producer",
")",
"Len",
"(",
")",
"int",
"{",
"return",
"len",
"(",
"p",
".",
"produceChannel",
")",
"+",
"len",
"(",
"p",
".",
"events",
")",
"+",
"int",
"(",
"C",
".",
"rd_kafka_outq_len",
"(",
"p",
".",
"handle",
".",
"rk",
")",
")",
"\n",
"}"
] | // Len returns the number of messages and requests waiting to be transmitted to the broker
// as well as delivery reports queued for the application.
// Includes messages on ProduceChannel. | [
"Len",
"returns",
"the",
"number",
"of",
"messages",
"and",
"requests",
"waiting",
"to",
"be",
"transmitted",
"to",
"the",
"broker",
"as",
"well",
"as",
"delivery",
"reports",
"queued",
"for",
"the",
"application",
".",
"Includes",
"messages",
"on",
"ProduceChannel",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/producer.go#L321-L323 |
164,034 | confluentinc/confluent-kafka-go | kafka/producer.go | Flush | func (p *Producer) Flush(timeoutMs int) int {
termChan := make(chan bool) // unused stand-in termChan
d, _ := time.ParseDuration(fmt.Sprintf("%dms", timeoutMs))
tEnd := time.Now().Add(d)
for p.Len() > 0 {
remain := tEnd.Sub(time.Now()).Seconds()
if remain <= 0.0 {
return p.Len()
}
p.handle.eventPoll(p.events,
int(math.Min(100, remain*1000)), 1000, termChan)
}
return 0
} | go | func (p *Producer) Flush(timeoutMs int) int {
termChan := make(chan bool) // unused stand-in termChan
d, _ := time.ParseDuration(fmt.Sprintf("%dms", timeoutMs))
tEnd := time.Now().Add(d)
for p.Len() > 0 {
remain := tEnd.Sub(time.Now()).Seconds()
if remain <= 0.0 {
return p.Len()
}
p.handle.eventPoll(p.events,
int(math.Min(100, remain*1000)), 1000, termChan)
}
return 0
} | [
"func",
"(",
"p",
"*",
"Producer",
")",
"Flush",
"(",
"timeoutMs",
"int",
")",
"int",
"{",
"termChan",
":=",
"make",
"(",
"chan",
"bool",
")",
"// unused stand-in termChan",
"\n\n",
"d",
",",
"_",
":=",
"time",
".",
"ParseDuration",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"timeoutMs",
")",
")",
"\n",
"tEnd",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"d",
")",
"\n",
"for",
"p",
".",
"Len",
"(",
")",
">",
"0",
"{",
"remain",
":=",
"tEnd",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
")",
".",
"Seconds",
"(",
")",
"\n",
"if",
"remain",
"<=",
"0.0",
"{",
"return",
"p",
".",
"Len",
"(",
")",
"\n",
"}",
"\n\n",
"p",
".",
"handle",
".",
"eventPoll",
"(",
"p",
".",
"events",
",",
"int",
"(",
"math",
".",
"Min",
"(",
"100",
",",
"remain",
"*",
"1000",
")",
")",
",",
"1000",
",",
"termChan",
")",
"\n",
"}",
"\n\n",
"return",
"0",
"\n",
"}"
] | // Flush and wait for outstanding messages and requests to complete delivery.
// Includes messages on ProduceChannel.
// Runs until value reaches zero or on timeoutMs.
// Returns the number of outstanding events still un-flushed. | [
"Flush",
"and",
"wait",
"for",
"outstanding",
"messages",
"and",
"requests",
"to",
"complete",
"delivery",
".",
"Includes",
"messages",
"on",
"ProduceChannel",
".",
"Runs",
"until",
"value",
"reaches",
"zero",
"or",
"on",
"timeoutMs",
".",
"Returns",
"the",
"number",
"of",
"outstanding",
"events",
"still",
"un",
"-",
"flushed",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/producer.go#L329-L345 |
164,035 | confluentinc/confluent-kafka-go | kafka/producer.go | Close | func (p *Producer) Close() {
// Wait for poller() (signaled by closing pollerTermChan)
// and channel_producer() (signaled by closing ProduceChannel)
close(p.pollerTermChan)
close(p.produceChannel)
p.handle.waitTerminated(2)
close(p.events)
p.handle.cleanup()
C.rd_kafka_destroy(p.handle.rk)
} | go | func (p *Producer) Close() {
// Wait for poller() (signaled by closing pollerTermChan)
// and channel_producer() (signaled by closing ProduceChannel)
close(p.pollerTermChan)
close(p.produceChannel)
p.handle.waitTerminated(2)
close(p.events)
p.handle.cleanup()
C.rd_kafka_destroy(p.handle.rk)
} | [
"func",
"(",
"p",
"*",
"Producer",
")",
"Close",
"(",
")",
"{",
"// Wait for poller() (signaled by closing pollerTermChan)",
"// and channel_producer() (signaled by closing ProduceChannel)",
"close",
"(",
"p",
".",
"pollerTermChan",
")",
"\n",
"close",
"(",
"p",
".",
"produceChannel",
")",
"\n",
"p",
".",
"handle",
".",
"waitTerminated",
"(",
"2",
")",
"\n\n",
"close",
"(",
"p",
".",
"events",
")",
"\n\n",
"p",
".",
"handle",
".",
"cleanup",
"(",
")",
"\n\n",
"C",
".",
"rd_kafka_destroy",
"(",
"p",
".",
"handle",
".",
"rk",
")",
"\n",
"}"
] | // Close a Producer instance.
// The Producer object or its channels are no longer usable after this call. | [
"Close",
"a",
"Producer",
"instance",
".",
"The",
"Producer",
"object",
"or",
"its",
"channels",
"are",
"no",
"longer",
"usable",
"after",
"this",
"call",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/producer.go#L349-L361 |
164,036 | confluentinc/confluent-kafka-go | kafka/producer.go | channelProducer | func channelProducer(p *Producer) {
for m := range p.produceChannel {
err := p.produce(m, C.RD_KAFKA_MSG_F_BLOCK, nil)
if err != nil {
m.TopicPartition.Error = err
p.events <- m
}
}
p.handle.terminatedChan <- "channelProducer"
} | go | func channelProducer(p *Producer) {
for m := range p.produceChannel {
err := p.produce(m, C.RD_KAFKA_MSG_F_BLOCK, nil)
if err != nil {
m.TopicPartition.Error = err
p.events <- m
}
}
p.handle.terminatedChan <- "channelProducer"
} | [
"func",
"channelProducer",
"(",
"p",
"*",
"Producer",
")",
"{",
"for",
"m",
":=",
"range",
"p",
".",
"produceChannel",
"{",
"err",
":=",
"p",
".",
"produce",
"(",
"m",
",",
"C",
".",
"RD_KAFKA_MSG_F_BLOCK",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"m",
".",
"TopicPartition",
".",
"Error",
"=",
"err",
"\n",
"p",
".",
"events",
"<-",
"m",
"\n",
"}",
"\n",
"}",
"\n\n",
"p",
".",
"handle",
".",
"terminatedChan",
"<-",
"\"",
"\"",
"\n",
"}"
] | // channel_producer serves the ProduceChannel channel | [
"channel_producer",
"serves",
"the",
"ProduceChannel",
"channel"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/producer.go#L471-L482 |
164,037 | confluentinc/confluent-kafka-go | kafka/producer.go | poller | func poller(p *Producer, termChan chan bool) {
out:
for true {
select {
case _ = <-termChan:
break out
default:
_, term := p.handle.eventPoll(p.events, 100, 1000, termChan)
if term {
break out
}
break
}
}
p.handle.terminatedChan <- "poller"
} | go | func poller(p *Producer, termChan chan bool) {
out:
for true {
select {
case _ = <-termChan:
break out
default:
_, term := p.handle.eventPoll(p.events, 100, 1000, termChan)
if term {
break out
}
break
}
}
p.handle.terminatedChan <- "poller"
} | [
"func",
"poller",
"(",
"p",
"*",
"Producer",
",",
"termChan",
"chan",
"bool",
")",
"{",
"out",
":",
"for",
"true",
"{",
"select",
"{",
"case",
"_",
"=",
"<-",
"termChan",
":",
"break",
"out",
"\n\n",
"default",
":",
"_",
",",
"term",
":=",
"p",
".",
"handle",
".",
"eventPoll",
"(",
"p",
".",
"events",
",",
"100",
",",
"1000",
",",
"termChan",
")",
"\n",
"if",
"term",
"{",
"break",
"out",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"p",
".",
"handle",
".",
"terminatedChan",
"<-",
"\"",
"\"",
"\n\n",
"}"
] | // poller polls the rd_kafka_t handle for events until signalled for termination | [
"poller",
"polls",
"the",
"rd_kafka_t",
"handle",
"for",
"events",
"until",
"signalled",
"for",
"termination"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/producer.go#L540-L558 |
164,038 | confluentinc/confluent-kafka-go | kafka/producer.go | QueryWatermarkOffsets | func (p *Producer) QueryWatermarkOffsets(topic string, partition int32, timeoutMs int) (low, high int64, err error) {
return queryWatermarkOffsets(p, topic, partition, timeoutMs)
} | go | func (p *Producer) QueryWatermarkOffsets(topic string, partition int32, timeoutMs int) (low, high int64, err error) {
return queryWatermarkOffsets(p, topic, partition, timeoutMs)
} | [
"func",
"(",
"p",
"*",
"Producer",
")",
"QueryWatermarkOffsets",
"(",
"topic",
"string",
",",
"partition",
"int32",
",",
"timeoutMs",
"int",
")",
"(",
"low",
",",
"high",
"int64",
",",
"err",
"error",
")",
"{",
"return",
"queryWatermarkOffsets",
"(",
"p",
",",
"topic",
",",
"partition",
",",
"timeoutMs",
")",
"\n",
"}"
] | // QueryWatermarkOffsets returns the broker's low and high offsets for the given topic
// and partition. | [
"QueryWatermarkOffsets",
"returns",
"the",
"broker",
"s",
"low",
"and",
"high",
"offsets",
"for",
"the",
"given",
"topic",
"and",
"partition",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/producer.go#L571-L573 |
164,039 | confluentinc/confluent-kafka-go | kafka/message.go | String | func (m *Message) String() string {
var topic string
if m.TopicPartition.Topic != nil {
topic = *m.TopicPartition.Topic
} else {
topic = ""
}
return fmt.Sprintf("%s[%d]@%s", topic, m.TopicPartition.Partition, m.TopicPartition.Offset)
} | go | func (m *Message) String() string {
var topic string
if m.TopicPartition.Topic != nil {
topic = *m.TopicPartition.Topic
} else {
topic = ""
}
return fmt.Sprintf("%s[%d]@%s", topic, m.TopicPartition.Partition, m.TopicPartition.Offset)
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"String",
"(",
")",
"string",
"{",
"var",
"topic",
"string",
"\n",
"if",
"m",
".",
"TopicPartition",
".",
"Topic",
"!=",
"nil",
"{",
"topic",
"=",
"*",
"m",
".",
"TopicPartition",
".",
"Topic",
"\n",
"}",
"else",
"{",
"topic",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"topic",
",",
"m",
".",
"TopicPartition",
".",
"Partition",
",",
"m",
".",
"TopicPartition",
".",
"Offset",
")",
"\n",
"}"
] | // String returns a human readable representation of a Message.
// Key and payload are not represented. | [
"String",
"returns",
"a",
"human",
"readable",
"representation",
"of",
"a",
"Message",
".",
"Key",
"and",
"payload",
"are",
"not",
"represented",
"."
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/message.go#L85-L93 |
164,040 | confluentinc/confluent-kafka-go | kafka/message.go | setupMessageFromC | func (h *handle) setupMessageFromC(msg *Message, cmsg *C.rd_kafka_message_t) {
if cmsg.rkt != nil {
topic := h.getTopicNameFromRkt(cmsg.rkt)
msg.TopicPartition.Topic = &topic
}
msg.TopicPartition.Partition = int32(cmsg.partition)
if cmsg.payload != nil {
msg.Value = C.GoBytes(unsafe.Pointer(cmsg.payload), C.int(cmsg.len))
}
if cmsg.key != nil {
msg.Key = C.GoBytes(unsafe.Pointer(cmsg.key), C.int(cmsg.key_len))
}
msg.TopicPartition.Offset = Offset(cmsg.offset)
if cmsg.err != 0 {
msg.TopicPartition.Error = newError(cmsg.err)
}
} | go | func (h *handle) setupMessageFromC(msg *Message, cmsg *C.rd_kafka_message_t) {
if cmsg.rkt != nil {
topic := h.getTopicNameFromRkt(cmsg.rkt)
msg.TopicPartition.Topic = &topic
}
msg.TopicPartition.Partition = int32(cmsg.partition)
if cmsg.payload != nil {
msg.Value = C.GoBytes(unsafe.Pointer(cmsg.payload), C.int(cmsg.len))
}
if cmsg.key != nil {
msg.Key = C.GoBytes(unsafe.Pointer(cmsg.key), C.int(cmsg.key_len))
}
msg.TopicPartition.Offset = Offset(cmsg.offset)
if cmsg.err != 0 {
msg.TopicPartition.Error = newError(cmsg.err)
}
} | [
"func",
"(",
"h",
"*",
"handle",
")",
"setupMessageFromC",
"(",
"msg",
"*",
"Message",
",",
"cmsg",
"*",
"C",
".",
"rd_kafka_message_t",
")",
"{",
"if",
"cmsg",
".",
"rkt",
"!=",
"nil",
"{",
"topic",
":=",
"h",
".",
"getTopicNameFromRkt",
"(",
"cmsg",
".",
"rkt",
")",
"\n",
"msg",
".",
"TopicPartition",
".",
"Topic",
"=",
"&",
"topic",
"\n",
"}",
"\n",
"msg",
".",
"TopicPartition",
".",
"Partition",
"=",
"int32",
"(",
"cmsg",
".",
"partition",
")",
"\n",
"if",
"cmsg",
".",
"payload",
"!=",
"nil",
"{",
"msg",
".",
"Value",
"=",
"C",
".",
"GoBytes",
"(",
"unsafe",
".",
"Pointer",
"(",
"cmsg",
".",
"payload",
")",
",",
"C",
".",
"int",
"(",
"cmsg",
".",
"len",
")",
")",
"\n",
"}",
"\n",
"if",
"cmsg",
".",
"key",
"!=",
"nil",
"{",
"msg",
".",
"Key",
"=",
"C",
".",
"GoBytes",
"(",
"unsafe",
".",
"Pointer",
"(",
"cmsg",
".",
"key",
")",
",",
"C",
".",
"int",
"(",
"cmsg",
".",
"key_len",
")",
")",
"\n",
"}",
"\n",
"msg",
".",
"TopicPartition",
".",
"Offset",
"=",
"Offset",
"(",
"cmsg",
".",
"offset",
")",
"\n",
"if",
"cmsg",
".",
"err",
"!=",
"0",
"{",
"msg",
".",
"TopicPartition",
".",
"Error",
"=",
"newError",
"(",
"cmsg",
".",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // setupMessageFromC sets up a message object from a C rd_kafka_message_t | [
"setupMessageFromC",
"sets",
"up",
"a",
"message",
"object",
"from",
"a",
"C",
"rd_kafka_message_t"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/message.go#L132-L148 |
164,041 | confluentinc/confluent-kafka-go | kafka/message.go | messageToC | func (h *handle) messageToC(msg *Message, cmsg *C.rd_kafka_message_t) {
var valp unsafe.Pointer
var keyp unsafe.Pointer
// to circumvent Cgo constraints we need to allocate C heap memory
// for both Value and Key (one allocation back to back)
// and copy the bytes from Value and Key to the C memory.
// We later tell librdkafka (in produce()) to free the
// C memory pointer when it is done.
var payload unsafe.Pointer
valueLen := 0
keyLen := 0
if msg.Value != nil {
valueLen = len(msg.Value)
}
if msg.Key != nil {
keyLen = len(msg.Key)
}
allocLen := valueLen + keyLen
if allocLen > 0 {
payload = C.malloc(C.size_t(allocLen))
if valueLen > 0 {
copy((*[1 << 30]byte)(payload)[0:valueLen], msg.Value)
valp = payload
}
if keyLen > 0 {
copy((*[1 << 30]byte)(payload)[valueLen:allocLen], msg.Key)
keyp = unsafe.Pointer(&((*[1 << 31]byte)(payload)[valueLen]))
}
}
cmsg.rkt = h.getRktFromMessage(msg)
cmsg.partition = C.int32_t(msg.TopicPartition.Partition)
cmsg.payload = valp
cmsg.len = C.size_t(valueLen)
cmsg.key = keyp
cmsg.key_len = C.size_t(keyLen)
cmsg._private = nil
} | go | func (h *handle) messageToC(msg *Message, cmsg *C.rd_kafka_message_t) {
var valp unsafe.Pointer
var keyp unsafe.Pointer
// to circumvent Cgo constraints we need to allocate C heap memory
// for both Value and Key (one allocation back to back)
// and copy the bytes from Value and Key to the C memory.
// We later tell librdkafka (in produce()) to free the
// C memory pointer when it is done.
var payload unsafe.Pointer
valueLen := 0
keyLen := 0
if msg.Value != nil {
valueLen = len(msg.Value)
}
if msg.Key != nil {
keyLen = len(msg.Key)
}
allocLen := valueLen + keyLen
if allocLen > 0 {
payload = C.malloc(C.size_t(allocLen))
if valueLen > 0 {
copy((*[1 << 30]byte)(payload)[0:valueLen], msg.Value)
valp = payload
}
if keyLen > 0 {
copy((*[1 << 30]byte)(payload)[valueLen:allocLen], msg.Key)
keyp = unsafe.Pointer(&((*[1 << 31]byte)(payload)[valueLen]))
}
}
cmsg.rkt = h.getRktFromMessage(msg)
cmsg.partition = C.int32_t(msg.TopicPartition.Partition)
cmsg.payload = valp
cmsg.len = C.size_t(valueLen)
cmsg.key = keyp
cmsg.key_len = C.size_t(keyLen)
cmsg._private = nil
} | [
"func",
"(",
"h",
"*",
"handle",
")",
"messageToC",
"(",
"msg",
"*",
"Message",
",",
"cmsg",
"*",
"C",
".",
"rd_kafka_message_t",
")",
"{",
"var",
"valp",
"unsafe",
".",
"Pointer",
"\n",
"var",
"keyp",
"unsafe",
".",
"Pointer",
"\n\n",
"// to circumvent Cgo constraints we need to allocate C heap memory",
"// for both Value and Key (one allocation back to back)",
"// and copy the bytes from Value and Key to the C memory.",
"// We later tell librdkafka (in produce()) to free the",
"// C memory pointer when it is done.",
"var",
"payload",
"unsafe",
".",
"Pointer",
"\n\n",
"valueLen",
":=",
"0",
"\n",
"keyLen",
":=",
"0",
"\n",
"if",
"msg",
".",
"Value",
"!=",
"nil",
"{",
"valueLen",
"=",
"len",
"(",
"msg",
".",
"Value",
")",
"\n",
"}",
"\n",
"if",
"msg",
".",
"Key",
"!=",
"nil",
"{",
"keyLen",
"=",
"len",
"(",
"msg",
".",
"Key",
")",
"\n",
"}",
"\n\n",
"allocLen",
":=",
"valueLen",
"+",
"keyLen",
"\n",
"if",
"allocLen",
">",
"0",
"{",
"payload",
"=",
"C",
".",
"malloc",
"(",
"C",
".",
"size_t",
"(",
"allocLen",
")",
")",
"\n",
"if",
"valueLen",
">",
"0",
"{",
"copy",
"(",
"(",
"*",
"[",
"1",
"<<",
"30",
"]",
"byte",
")",
"(",
"payload",
")",
"[",
"0",
":",
"valueLen",
"]",
",",
"msg",
".",
"Value",
")",
"\n",
"valp",
"=",
"payload",
"\n",
"}",
"\n",
"if",
"keyLen",
">",
"0",
"{",
"copy",
"(",
"(",
"*",
"[",
"1",
"<<",
"30",
"]",
"byte",
")",
"(",
"payload",
")",
"[",
"valueLen",
":",
"allocLen",
"]",
",",
"msg",
".",
"Key",
")",
"\n",
"keyp",
"=",
"unsafe",
".",
"Pointer",
"(",
"&",
"(",
"(",
"*",
"[",
"1",
"<<",
"31",
"]",
"byte",
")",
"(",
"payload",
")",
"[",
"valueLen",
"]",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"cmsg",
".",
"rkt",
"=",
"h",
".",
"getRktFromMessage",
"(",
"msg",
")",
"\n",
"cmsg",
".",
"partition",
"=",
"C",
".",
"int32_t",
"(",
"msg",
".",
"TopicPartition",
".",
"Partition",
")",
"\n",
"cmsg",
".",
"payload",
"=",
"valp",
"\n",
"cmsg",
".",
"len",
"=",
"C",
".",
"size_t",
"(",
"valueLen",
")",
"\n",
"cmsg",
".",
"key",
"=",
"keyp",
"\n",
"cmsg",
".",
"key_len",
"=",
"C",
".",
"size_t",
"(",
"keyLen",
")",
"\n",
"cmsg",
".",
"_private",
"=",
"nil",
"\n",
"}"
] | // messageToC sets up cmsg as a clone of msg | [
"messageToC",
"sets",
"up",
"cmsg",
"as",
"a",
"clone",
"of",
"msg"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/message.go#L161-L201 |
164,042 | confluentinc/confluent-kafka-go | kafka/message.go | messageToCDummy | func (h *handle) messageToCDummy(msg *Message) {
var cmsg C.rd_kafka_message_t
h.messageToC(msg, &cmsg)
} | go | func (h *handle) messageToCDummy(msg *Message) {
var cmsg C.rd_kafka_message_t
h.messageToC(msg, &cmsg)
} | [
"func",
"(",
"h",
"*",
"handle",
")",
"messageToCDummy",
"(",
"msg",
"*",
"Message",
")",
"{",
"var",
"cmsg",
"C",
".",
"rd_kafka_message_t",
"\n",
"h",
".",
"messageToC",
"(",
"msg",
",",
"&",
"cmsg",
")",
"\n",
"}"
] | // used for testing messageToC performance | [
"used",
"for",
"testing",
"messageToC",
"performance"
] | cfbc1edb6a54515310a0c7840bf4a24159b51876 | https://github.com/confluentinc/confluent-kafka-go/blob/cfbc1edb6a54515310a0c7840bf4a24159b51876/kafka/message.go#L204-L207 |
164,043 | nats-io/gnatsd | server/opts.go | Clone | func (o *Options) Clone() *Options {
if o == nil {
return nil
}
clone := &Options{}
*clone = *o
if o.Users != nil {
clone.Users = make([]*User, len(o.Users))
for i, user := range o.Users {
clone.Users[i] = user.clone()
}
}
if o.Nkeys != nil {
clone.Nkeys = make([]*NkeyUser, len(o.Nkeys))
for i, nkey := range o.Nkeys {
clone.Nkeys[i] = nkey.clone()
}
}
if o.Routes != nil {
clone.Routes = deepCopyURLs(o.Routes)
}
if o.TLSConfig != nil {
clone.TLSConfig = o.TLSConfig.Clone()
}
if o.Cluster.TLSConfig != nil {
clone.Cluster.TLSConfig = o.Cluster.TLSConfig.Clone()
}
if o.Gateway.TLSConfig != nil {
clone.Gateway.TLSConfig = o.Gateway.TLSConfig.Clone()
}
if len(o.Gateway.Gateways) > 0 {
clone.Gateway.Gateways = make([]*RemoteGatewayOpts, len(o.Gateway.Gateways))
for i, g := range o.Gateway.Gateways {
clone.Gateway.Gateways[i] = g.clone()
}
}
// FIXME(dlc) - clone leaf node stuff.
return clone
} | go | func (o *Options) Clone() *Options {
if o == nil {
return nil
}
clone := &Options{}
*clone = *o
if o.Users != nil {
clone.Users = make([]*User, len(o.Users))
for i, user := range o.Users {
clone.Users[i] = user.clone()
}
}
if o.Nkeys != nil {
clone.Nkeys = make([]*NkeyUser, len(o.Nkeys))
for i, nkey := range o.Nkeys {
clone.Nkeys[i] = nkey.clone()
}
}
if o.Routes != nil {
clone.Routes = deepCopyURLs(o.Routes)
}
if o.TLSConfig != nil {
clone.TLSConfig = o.TLSConfig.Clone()
}
if o.Cluster.TLSConfig != nil {
clone.Cluster.TLSConfig = o.Cluster.TLSConfig.Clone()
}
if o.Gateway.TLSConfig != nil {
clone.Gateway.TLSConfig = o.Gateway.TLSConfig.Clone()
}
if len(o.Gateway.Gateways) > 0 {
clone.Gateway.Gateways = make([]*RemoteGatewayOpts, len(o.Gateway.Gateways))
for i, g := range o.Gateway.Gateways {
clone.Gateway.Gateways[i] = g.clone()
}
}
// FIXME(dlc) - clone leaf node stuff.
return clone
} | [
"func",
"(",
"o",
"*",
"Options",
")",
"Clone",
"(",
")",
"*",
"Options",
"{",
"if",
"o",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"clone",
":=",
"&",
"Options",
"{",
"}",
"\n",
"*",
"clone",
"=",
"*",
"o",
"\n",
"if",
"o",
".",
"Users",
"!=",
"nil",
"{",
"clone",
".",
"Users",
"=",
"make",
"(",
"[",
"]",
"*",
"User",
",",
"len",
"(",
"o",
".",
"Users",
")",
")",
"\n",
"for",
"i",
",",
"user",
":=",
"range",
"o",
".",
"Users",
"{",
"clone",
".",
"Users",
"[",
"i",
"]",
"=",
"user",
".",
"clone",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"o",
".",
"Nkeys",
"!=",
"nil",
"{",
"clone",
".",
"Nkeys",
"=",
"make",
"(",
"[",
"]",
"*",
"NkeyUser",
",",
"len",
"(",
"o",
".",
"Nkeys",
")",
")",
"\n",
"for",
"i",
",",
"nkey",
":=",
"range",
"o",
".",
"Nkeys",
"{",
"clone",
".",
"Nkeys",
"[",
"i",
"]",
"=",
"nkey",
".",
"clone",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"o",
".",
"Routes",
"!=",
"nil",
"{",
"clone",
".",
"Routes",
"=",
"deepCopyURLs",
"(",
"o",
".",
"Routes",
")",
"\n",
"}",
"\n",
"if",
"o",
".",
"TLSConfig",
"!=",
"nil",
"{",
"clone",
".",
"TLSConfig",
"=",
"o",
".",
"TLSConfig",
".",
"Clone",
"(",
")",
"\n",
"}",
"\n",
"if",
"o",
".",
"Cluster",
".",
"TLSConfig",
"!=",
"nil",
"{",
"clone",
".",
"Cluster",
".",
"TLSConfig",
"=",
"o",
".",
"Cluster",
".",
"TLSConfig",
".",
"Clone",
"(",
")",
"\n",
"}",
"\n",
"if",
"o",
".",
"Gateway",
".",
"TLSConfig",
"!=",
"nil",
"{",
"clone",
".",
"Gateway",
".",
"TLSConfig",
"=",
"o",
".",
"Gateway",
".",
"TLSConfig",
".",
"Clone",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"o",
".",
"Gateway",
".",
"Gateways",
")",
">",
"0",
"{",
"clone",
".",
"Gateway",
".",
"Gateways",
"=",
"make",
"(",
"[",
"]",
"*",
"RemoteGatewayOpts",
",",
"len",
"(",
"o",
".",
"Gateway",
".",
"Gateways",
")",
")",
"\n",
"for",
"i",
",",
"g",
":=",
"range",
"o",
".",
"Gateway",
".",
"Gateways",
"{",
"clone",
".",
"Gateway",
".",
"Gateways",
"[",
"i",
"]",
"=",
"g",
".",
"clone",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// FIXME(dlc) - clone leaf node stuff.",
"return",
"clone",
"\n",
"}"
] | // Clone performs a deep copy of the Options struct, returning a new clone
// with all values copied. | [
"Clone",
"performs",
"a",
"deep",
"copy",
"of",
"the",
"Options",
"struct",
"returning",
"a",
"new",
"clone",
"with",
"all",
"values",
"copied",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L193-L232 |
164,044 | nats-io/gnatsd | server/opts.go | unwrapValue | func unwrapValue(v interface{}) (token, interface{}) {
switch tk := v.(type) {
case token:
return tk, tk.Value()
default:
return nil, v
}
} | go | func unwrapValue(v interface{}) (token, interface{}) {
switch tk := v.(type) {
case token:
return tk, tk.Value()
default:
return nil, v
}
} | [
"func",
"unwrapValue",
"(",
"v",
"interface",
"{",
"}",
")",
"(",
"token",
",",
"interface",
"{",
"}",
")",
"{",
"switch",
"tk",
":=",
"v",
".",
"(",
"type",
")",
"{",
"case",
"token",
":",
"return",
"tk",
",",
"tk",
".",
"Value",
"(",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"v",
"\n",
"}",
"\n",
"}"
] | // unwrapValue can be used to get the token and value from an item
// to be able to report the line number in case of an incorrect
// configuration. | [
"unwrapValue",
"can",
"be",
"used",
"to",
"get",
"the",
"token",
"and",
"value",
"from",
"an",
"item",
"to",
"be",
"able",
"to",
"report",
"the",
"line",
"number",
"in",
"case",
"of",
"an",
"incorrect",
"configuration",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L327-L334 |
164,045 | nats-io/gnatsd | server/opts.go | getTLSConfig | func getTLSConfig(tk token) (*tls.Config, *TLSConfigOpts, error) {
tc, err := parseTLS(tk)
if err != nil {
return nil, nil, err
}
config, err := GenTLSConfig(tc)
if err != nil {
err := &configErr{tk, err.Error()}
return nil, nil, err
}
// For clusters/gateways, we will force strict verification. We also act
// as both client and server, so will mirror the rootCA to the
// clientCA pool.
config.ClientAuth = tls.RequireAndVerifyClientCert
config.RootCAs = config.ClientCAs
return config, tc, nil
} | go | func getTLSConfig(tk token) (*tls.Config, *TLSConfigOpts, error) {
tc, err := parseTLS(tk)
if err != nil {
return nil, nil, err
}
config, err := GenTLSConfig(tc)
if err != nil {
err := &configErr{tk, err.Error()}
return nil, nil, err
}
// For clusters/gateways, we will force strict verification. We also act
// as both client and server, so will mirror the rootCA to the
// clientCA pool.
config.ClientAuth = tls.RequireAndVerifyClientCert
config.RootCAs = config.ClientCAs
return config, tc, nil
} | [
"func",
"getTLSConfig",
"(",
"tk",
"token",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"*",
"TLSConfigOpts",
",",
"error",
")",
"{",
"tc",
",",
"err",
":=",
"parseTLS",
"(",
"tk",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"config",
",",
"err",
":=",
"GenTLSConfig",
"(",
"tc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
":=",
"&",
"configErr",
"{",
"tk",
",",
"err",
".",
"Error",
"(",
")",
"}",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// For clusters/gateways, we will force strict verification. We also act",
"// as both client and server, so will mirror the rootCA to the",
"// clientCA pool.",
"config",
".",
"ClientAuth",
"=",
"tls",
".",
"RequireAndVerifyClientCert",
"\n",
"config",
".",
"RootCAs",
"=",
"config",
".",
"ClientCAs",
"\n",
"return",
"config",
",",
"tc",
",",
"nil",
"\n",
"}"
] | // Parse TLS and returns a TLSConfig and TLSTimeout.
// Used by cluster and gateway parsing. | [
"Parse",
"TLS",
"and",
"returns",
"a",
"TLSConfig",
"and",
"TLSTimeout",
".",
"Used",
"by",
"cluster",
"and",
"gateway",
"parsing",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L1079-L1095 |
164,046 | nats-io/gnatsd | server/opts.go | parseAccount | func parseAccount(v map[string]interface{}, errors, warnings *[]error) (string, string, error) {
var accountName, subject string
for mk, mv := range v {
tk, mv := unwrapValue(mv)
switch strings.ToLower(mk) {
case "account":
accountName = mv.(string)
case "subject":
subject = mv.(string)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
}
}
return accountName, subject, nil
} | go | func parseAccount(v map[string]interface{}, errors, warnings *[]error) (string, string, error) {
var accountName, subject string
for mk, mv := range v {
tk, mv := unwrapValue(mv)
switch strings.ToLower(mk) {
case "account":
accountName = mv.(string)
case "subject":
subject = mv.(string)
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
}
}
return accountName, subject, nil
} | [
"func",
"parseAccount",
"(",
"v",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"errors",
",",
"warnings",
"*",
"[",
"]",
"error",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"var",
"accountName",
",",
"subject",
"string",
"\n",
"for",
"mk",
",",
"mv",
":=",
"range",
"v",
"{",
"tk",
",",
"mv",
":=",
"unwrapValue",
"(",
"mv",
")",
"\n",
"switch",
"strings",
".",
"ToLower",
"(",
"mk",
")",
"{",
"case",
"\"",
"\"",
":",
"accountName",
"=",
"mv",
".",
"(",
"string",
")",
"\n",
"case",
"\"",
"\"",
":",
"subject",
"=",
"mv",
".",
"(",
"string",
")",
"\n",
"default",
":",
"if",
"!",
"tk",
".",
"IsUsedVariable",
"(",
")",
"{",
"err",
":=",
"&",
"unknownConfigFieldErr",
"{",
"field",
":",
"mk",
",",
"configErr",
":",
"configErr",
"{",
"token",
":",
"tk",
",",
"}",
",",
"}",
"\n",
"*",
"errors",
"=",
"append",
"(",
"*",
"errors",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"accountName",
",",
"subject",
",",
"nil",
"\n",
"}"
] | // Helper to parse an embedded account description for imported services or streams. | [
"Helper",
"to",
"parse",
"an",
"embedded",
"account",
"description",
"for",
"imported",
"services",
"or",
"streams",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L1473-L1495 |
164,047 | nats-io/gnatsd | server/opts.go | parseAuthorization | func parseAuthorization(v interface{}, opts *Options, errors *[]error, warnings *[]error) (*authorization, error) {
var (
am map[string]interface{}
tk token
auth = &authorization{}
)
_, v = unwrapValue(v)
am = v.(map[string]interface{})
for mk, mv := range am {
tk, mv = unwrapValue(mv)
switch strings.ToLower(mk) {
case "user", "username":
auth.user = mv.(string)
case "pass", "password":
auth.pass = mv.(string)
case "token":
auth.token = mv.(string)
case "timeout":
at := float64(1)
switch mv := mv.(type) {
case int64:
at = float64(mv)
case float64:
at = mv
}
auth.timeout = at
case "users":
nkeys, users, err := parseUsers(tk, opts, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
auth.users = users
auth.nkeys = nkeys
case "default_permission", "default_permissions", "permissions":
permissions, err := parseUserPermissions(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
auth.defaultPermissions = permissions
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
continue
}
// Now check for permission defaults with multiple users, etc.
if auth.users != nil && auth.defaultPermissions != nil {
for _, user := range auth.users {
if user.Permissions == nil {
user.Permissions = auth.defaultPermissions
}
}
}
}
return auth, nil
} | go | func parseAuthorization(v interface{}, opts *Options, errors *[]error, warnings *[]error) (*authorization, error) {
var (
am map[string]interface{}
tk token
auth = &authorization{}
)
_, v = unwrapValue(v)
am = v.(map[string]interface{})
for mk, mv := range am {
tk, mv = unwrapValue(mv)
switch strings.ToLower(mk) {
case "user", "username":
auth.user = mv.(string)
case "pass", "password":
auth.pass = mv.(string)
case "token":
auth.token = mv.(string)
case "timeout":
at := float64(1)
switch mv := mv.(type) {
case int64:
at = float64(mv)
case float64:
at = mv
}
auth.timeout = at
case "users":
nkeys, users, err := parseUsers(tk, opts, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
auth.users = users
auth.nkeys = nkeys
case "default_permission", "default_permissions", "permissions":
permissions, err := parseUserPermissions(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
auth.defaultPermissions = permissions
default:
if !tk.IsUsedVariable() {
err := &unknownConfigFieldErr{
field: mk,
configErr: configErr{
token: tk,
},
}
*errors = append(*errors, err)
}
continue
}
// Now check for permission defaults with multiple users, etc.
if auth.users != nil && auth.defaultPermissions != nil {
for _, user := range auth.users {
if user.Permissions == nil {
user.Permissions = auth.defaultPermissions
}
}
}
}
return auth, nil
} | [
"func",
"parseAuthorization",
"(",
"v",
"interface",
"{",
"}",
",",
"opts",
"*",
"Options",
",",
"errors",
"*",
"[",
"]",
"error",
",",
"warnings",
"*",
"[",
"]",
"error",
")",
"(",
"*",
"authorization",
",",
"error",
")",
"{",
"var",
"(",
"am",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"tk",
"token",
"\n",
"auth",
"=",
"&",
"authorization",
"{",
"}",
"\n",
")",
"\n\n",
"_",
",",
"v",
"=",
"unwrapValue",
"(",
"v",
")",
"\n",
"am",
"=",
"v",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"mk",
",",
"mv",
":=",
"range",
"am",
"{",
"tk",
",",
"mv",
"=",
"unwrapValue",
"(",
"mv",
")",
"\n",
"switch",
"strings",
".",
"ToLower",
"(",
"mk",
")",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"auth",
".",
"user",
"=",
"mv",
".",
"(",
"string",
")",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"auth",
".",
"pass",
"=",
"mv",
".",
"(",
"string",
")",
"\n",
"case",
"\"",
"\"",
":",
"auth",
".",
"token",
"=",
"mv",
".",
"(",
"string",
")",
"\n",
"case",
"\"",
"\"",
":",
"at",
":=",
"float64",
"(",
"1",
")",
"\n",
"switch",
"mv",
":=",
"mv",
".",
"(",
"type",
")",
"{",
"case",
"int64",
":",
"at",
"=",
"float64",
"(",
"mv",
")",
"\n",
"case",
"float64",
":",
"at",
"=",
"mv",
"\n",
"}",
"\n",
"auth",
".",
"timeout",
"=",
"at",
"\n",
"case",
"\"",
"\"",
":",
"nkeys",
",",
"users",
",",
"err",
":=",
"parseUsers",
"(",
"tk",
",",
"opts",
",",
"errors",
",",
"warnings",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"*",
"errors",
"=",
"append",
"(",
"*",
"errors",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"auth",
".",
"users",
"=",
"users",
"\n",
"auth",
".",
"nkeys",
"=",
"nkeys",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"permissions",
",",
"err",
":=",
"parseUserPermissions",
"(",
"tk",
",",
"errors",
",",
"warnings",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"*",
"errors",
"=",
"append",
"(",
"*",
"errors",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"auth",
".",
"defaultPermissions",
"=",
"permissions",
"\n",
"default",
":",
"if",
"!",
"tk",
".",
"IsUsedVariable",
"(",
")",
"{",
"err",
":=",
"&",
"unknownConfigFieldErr",
"{",
"field",
":",
"mk",
",",
"configErr",
":",
"configErr",
"{",
"token",
":",
"tk",
",",
"}",
",",
"}",
"\n",
"*",
"errors",
"=",
"append",
"(",
"*",
"errors",
",",
"err",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Now check for permission defaults with multiple users, etc.",
"if",
"auth",
".",
"users",
"!=",
"nil",
"&&",
"auth",
".",
"defaultPermissions",
"!=",
"nil",
"{",
"for",
"_",
",",
"user",
":=",
"range",
"auth",
".",
"users",
"{",
"if",
"user",
".",
"Permissions",
"==",
"nil",
"{",
"user",
".",
"Permissions",
"=",
"auth",
".",
"defaultPermissions",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"}",
"\n",
"return",
"auth",
",",
"nil",
"\n",
"}"
] | // Helper function to parse Authorization configs. | [
"Helper",
"function",
"to",
"parse",
"Authorization",
"configs",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L1676-L1742 |
164,048 | nats-io/gnatsd | server/opts.go | parseVariablePermissions | func parseVariablePermissions(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
switch vv := v.(type) {
case map[string]interface{}:
// New style with allow and/or deny properties.
return parseSubjectPermission(vv, errors, warnings)
default:
// Old style
return parseOldPermissionStyle(v, errors, warnings)
}
} | go | func parseVariablePermissions(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
switch vv := v.(type) {
case map[string]interface{}:
// New style with allow and/or deny properties.
return parseSubjectPermission(vv, errors, warnings)
default:
// Old style
return parseOldPermissionStyle(v, errors, warnings)
}
} | [
"func",
"parseVariablePermissions",
"(",
"v",
"interface",
"{",
"}",
",",
"errors",
",",
"warnings",
"*",
"[",
"]",
"error",
")",
"(",
"*",
"SubjectPermission",
",",
"error",
")",
"{",
"switch",
"vv",
":=",
"v",
".",
"(",
"type",
")",
"{",
"case",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
":",
"// New style with allow and/or deny properties.",
"return",
"parseSubjectPermission",
"(",
"vv",
",",
"errors",
",",
"warnings",
")",
"\n",
"default",
":",
"// Old style",
"return",
"parseOldPermissionStyle",
"(",
"v",
",",
"errors",
",",
"warnings",
")",
"\n",
"}",
"\n",
"}"
] | // Top level parser for authorization configurations. | [
"Top",
"level",
"parser",
"for",
"authorization",
"configurations",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L1878-L1887 |
164,049 | nats-io/gnatsd | server/opts.go | parseOldPermissionStyle | func parseOldPermissionStyle(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
subjects, err := parseSubjects(v, errors, warnings)
if err != nil {
return nil, err
}
return &SubjectPermission{Allow: subjects}, nil
} | go | func parseOldPermissionStyle(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
subjects, err := parseSubjects(v, errors, warnings)
if err != nil {
return nil, err
}
return &SubjectPermission{Allow: subjects}, nil
} | [
"func",
"parseOldPermissionStyle",
"(",
"v",
"interface",
"{",
"}",
",",
"errors",
",",
"warnings",
"*",
"[",
"]",
"error",
")",
"(",
"*",
"SubjectPermission",
",",
"error",
")",
"{",
"subjects",
",",
"err",
":=",
"parseSubjects",
"(",
"v",
",",
"errors",
",",
"warnings",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"SubjectPermission",
"{",
"Allow",
":",
"subjects",
"}",
",",
"nil",
"\n",
"}"
] | // Helper function to parse old style authorization configs. | [
"Helper",
"function",
"to",
"parse",
"old",
"style",
"authorization",
"configs",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L1919-L1925 |
164,050 | nats-io/gnatsd | server/opts.go | parseSubjectPermission | func parseSubjectPermission(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
m := v.(map[string]interface{})
if len(m) == 0 {
return nil, nil
}
p := &SubjectPermission{}
for k, v := range m {
tk, _ := unwrapValue(v)
switch strings.ToLower(k) {
case "allow":
subjects, err := parseSubjects(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
p.Allow = subjects
case "deny":
subjects, err := parseSubjects(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
p.Deny = subjects
default:
if !tk.IsUsedVariable() {
err := &configErr{tk, fmt.Sprintf("Unknown field name %q parsing subject permissions, only 'allow' or 'deny' are permitted", k)}
*errors = append(*errors, err)
}
}
}
return p, nil
} | go | func parseSubjectPermission(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
m := v.(map[string]interface{})
if len(m) == 0 {
return nil, nil
}
p := &SubjectPermission{}
for k, v := range m {
tk, _ := unwrapValue(v)
switch strings.ToLower(k) {
case "allow":
subjects, err := parseSubjects(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
p.Allow = subjects
case "deny":
subjects, err := parseSubjects(tk, errors, warnings)
if err != nil {
*errors = append(*errors, err)
continue
}
p.Deny = subjects
default:
if !tk.IsUsedVariable() {
err := &configErr{tk, fmt.Sprintf("Unknown field name %q parsing subject permissions, only 'allow' or 'deny' are permitted", k)}
*errors = append(*errors, err)
}
}
}
return p, nil
} | [
"func",
"parseSubjectPermission",
"(",
"v",
"interface",
"{",
"}",
",",
"errors",
",",
"warnings",
"*",
"[",
"]",
"error",
")",
"(",
"*",
"SubjectPermission",
",",
"error",
")",
"{",
"m",
":=",
"v",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"len",
"(",
"m",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"p",
":=",
"&",
"SubjectPermission",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
"{",
"tk",
",",
"_",
":=",
"unwrapValue",
"(",
"v",
")",
"\n",
"switch",
"strings",
".",
"ToLower",
"(",
"k",
")",
"{",
"case",
"\"",
"\"",
":",
"subjects",
",",
"err",
":=",
"parseSubjects",
"(",
"tk",
",",
"errors",
",",
"warnings",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"*",
"errors",
"=",
"append",
"(",
"*",
"errors",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"p",
".",
"Allow",
"=",
"subjects",
"\n",
"case",
"\"",
"\"",
":",
"subjects",
",",
"err",
":=",
"parseSubjects",
"(",
"tk",
",",
"errors",
",",
"warnings",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"*",
"errors",
"=",
"append",
"(",
"*",
"errors",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"p",
".",
"Deny",
"=",
"subjects",
"\n",
"default",
":",
"if",
"!",
"tk",
".",
"IsUsedVariable",
"(",
")",
"{",
"err",
":=",
"&",
"configErr",
"{",
"tk",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"k",
")",
"}",
"\n",
"*",
"errors",
"=",
"append",
"(",
"*",
"errors",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"p",
",",
"nil",
"\n",
"}"
] | // Helper function to parse new style authorization into a SubjectPermission with Allow and Deny. | [
"Helper",
"function",
"to",
"parse",
"new",
"style",
"authorization",
"into",
"a",
"SubjectPermission",
"with",
"Allow",
"and",
"Deny",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L1928-L1959 |
164,051 | nats-io/gnatsd | server/opts.go | checkSubjectArray | func checkSubjectArray(sa []string) error {
for _, s := range sa {
if !IsValidSubject(s) {
return fmt.Errorf("subject %q is not a valid subject", s)
}
}
return nil
} | go | func checkSubjectArray(sa []string) error {
for _, s := range sa {
if !IsValidSubject(s) {
return fmt.Errorf("subject %q is not a valid subject", s)
}
}
return nil
} | [
"func",
"checkSubjectArray",
"(",
"sa",
"[",
"]",
"string",
")",
"error",
"{",
"for",
"_",
",",
"s",
":=",
"range",
"sa",
"{",
"if",
"!",
"IsValidSubject",
"(",
"s",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"s",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Helper function to validate subjects, etc for account permissioning. | [
"Helper",
"function",
"to",
"validate",
"subjects",
"etc",
"for",
"account",
"permissioning",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L1962-L1969 |
164,052 | nats-io/gnatsd | server/opts.go | PrintTLSHelpAndDie | func PrintTLSHelpAndDie() {
fmt.Printf("%s", tlsUsage)
for k := range cipherMap {
fmt.Printf(" %s\n", k)
}
fmt.Printf("\nAvailable curve preferences include:\n")
for k := range curvePreferenceMap {
fmt.Printf(" %s\n", k)
}
os.Exit(0)
} | go | func PrintTLSHelpAndDie() {
fmt.Printf("%s", tlsUsage)
for k := range cipherMap {
fmt.Printf(" %s\n", k)
}
fmt.Printf("\nAvailable curve preferences include:\n")
for k := range curvePreferenceMap {
fmt.Printf(" %s\n", k)
}
os.Exit(0)
} | [
"func",
"PrintTLSHelpAndDie",
"(",
")",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\"",
",",
"tlsUsage",
")",
"\n",
"for",
"k",
":=",
"range",
"cipherMap",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"k",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\\n",
"\"",
")",
"\n",
"for",
"k",
":=",
"range",
"curvePreferenceMap",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"k",
")",
"\n",
"}",
"\n",
"os",
".",
"Exit",
"(",
"0",
")",
"\n",
"}"
] | // PrintTLSHelpAndDie prints TLS usage and exits. | [
"PrintTLSHelpAndDie",
"prints",
"TLS",
"usage",
"and",
"exits",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L1972-L1982 |
164,053 | nats-io/gnatsd | server/opts.go | GenTLSConfig | func GenTLSConfig(tc *TLSConfigOpts) (*tls.Config, error) {
// Now load in cert and private key
cert, err := tls.LoadX509KeyPair(tc.CertFile, tc.KeyFile)
if err != nil {
return nil, fmt.Errorf("error parsing X509 certificate/key pair: %v", err)
}
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return nil, fmt.Errorf("error parsing certificate: %v", err)
}
// Create the tls.Config from our options.
// We will determine the cipher suites that we prefer.
// FIXME(dlc) change if ARM based.
config := tls.Config{
MinVersion: tls.VersionTLS12,
CipherSuites: tc.Ciphers,
PreferServerCipherSuites: true,
CurvePreferences: tc.CurvePreferences,
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: tc.Insecure,
}
// Require client certificates as needed
if tc.Verify {
config.ClientAuth = tls.RequireAndVerifyClientCert
}
// Add in CAs if applicable.
if tc.CaFile != "" {
rootPEM, err := ioutil.ReadFile(tc.CaFile)
if err != nil || rootPEM == nil {
return nil, err
}
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM(rootPEM)
if !ok {
return nil, fmt.Errorf("failed to parse root ca certificate")
}
config.ClientCAs = pool
}
return &config, nil
} | go | func GenTLSConfig(tc *TLSConfigOpts) (*tls.Config, error) {
// Now load in cert and private key
cert, err := tls.LoadX509KeyPair(tc.CertFile, tc.KeyFile)
if err != nil {
return nil, fmt.Errorf("error parsing X509 certificate/key pair: %v", err)
}
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return nil, fmt.Errorf("error parsing certificate: %v", err)
}
// Create the tls.Config from our options.
// We will determine the cipher suites that we prefer.
// FIXME(dlc) change if ARM based.
config := tls.Config{
MinVersion: tls.VersionTLS12,
CipherSuites: tc.Ciphers,
PreferServerCipherSuites: true,
CurvePreferences: tc.CurvePreferences,
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: tc.Insecure,
}
// Require client certificates as needed
if tc.Verify {
config.ClientAuth = tls.RequireAndVerifyClientCert
}
// Add in CAs if applicable.
if tc.CaFile != "" {
rootPEM, err := ioutil.ReadFile(tc.CaFile)
if err != nil || rootPEM == nil {
return nil, err
}
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM(rootPEM)
if !ok {
return nil, fmt.Errorf("failed to parse root ca certificate")
}
config.ClientCAs = pool
}
return &config, nil
} | [
"func",
"GenTLSConfig",
"(",
"tc",
"*",
"TLSConfigOpts",
")",
"(",
"*",
"tls",
".",
"Config",
",",
"error",
")",
"{",
"// Now load in cert and private key",
"cert",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"tc",
".",
"CertFile",
",",
"tc",
".",
"KeyFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cert",
".",
"Leaf",
",",
"err",
"=",
"x509",
".",
"ParseCertificate",
"(",
"cert",
".",
"Certificate",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Create the tls.Config from our options.",
"// We will determine the cipher suites that we prefer.",
"// FIXME(dlc) change if ARM based.",
"config",
":=",
"tls",
".",
"Config",
"{",
"MinVersion",
":",
"tls",
".",
"VersionTLS12",
",",
"CipherSuites",
":",
"tc",
".",
"Ciphers",
",",
"PreferServerCipherSuites",
":",
"true",
",",
"CurvePreferences",
":",
"tc",
".",
"CurvePreferences",
",",
"Certificates",
":",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
"}",
",",
"InsecureSkipVerify",
":",
"tc",
".",
"Insecure",
",",
"}",
"\n\n",
"// Require client certificates as needed",
"if",
"tc",
".",
"Verify",
"{",
"config",
".",
"ClientAuth",
"=",
"tls",
".",
"RequireAndVerifyClientCert",
"\n",
"}",
"\n",
"// Add in CAs if applicable.",
"if",
"tc",
".",
"CaFile",
"!=",
"\"",
"\"",
"{",
"rootPEM",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"tc",
".",
"CaFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"rootPEM",
"==",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"pool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"ok",
":=",
"pool",
".",
"AppendCertsFromPEM",
"(",
"rootPEM",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"config",
".",
"ClientCAs",
"=",
"pool",
"\n",
"}",
"\n\n",
"return",
"&",
"config",
",",
"nil",
"\n",
"}"
] | // GenTLSConfig loads TLS related configuration parameters. | [
"GenTLSConfig",
"loads",
"TLS",
"related",
"configuration",
"parameters",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L2105-L2148 |
164,054 | nats-io/gnatsd | server/opts.go | MergeOptions | func MergeOptions(fileOpts, flagOpts *Options) *Options {
if fileOpts == nil {
return flagOpts
}
if flagOpts == nil {
return fileOpts
}
// Merge the two, flagOpts override
opts := *fileOpts
if flagOpts.Port != 0 {
opts.Port = flagOpts.Port
}
if flagOpts.Host != "" {
opts.Host = flagOpts.Host
}
if flagOpts.ClientAdvertise != "" {
opts.ClientAdvertise = flagOpts.ClientAdvertise
}
if flagOpts.Username != "" {
opts.Username = flagOpts.Username
}
if flagOpts.Password != "" {
opts.Password = flagOpts.Password
}
if flagOpts.Authorization != "" {
opts.Authorization = flagOpts.Authorization
}
if flagOpts.HTTPPort != 0 {
opts.HTTPPort = flagOpts.HTTPPort
}
if flagOpts.Debug {
opts.Debug = true
}
if flagOpts.Trace {
opts.Trace = true
}
if flagOpts.Logtime {
opts.Logtime = true
}
if flagOpts.LogFile != "" {
opts.LogFile = flagOpts.LogFile
}
if flagOpts.PidFile != "" {
opts.PidFile = flagOpts.PidFile
}
if flagOpts.PortsFileDir != "" {
opts.PortsFileDir = flagOpts.PortsFileDir
}
if flagOpts.ProfPort != 0 {
opts.ProfPort = flagOpts.ProfPort
}
if flagOpts.Cluster.ListenStr != "" {
opts.Cluster.ListenStr = flagOpts.Cluster.ListenStr
}
if flagOpts.Cluster.NoAdvertise {
opts.Cluster.NoAdvertise = true
}
if flagOpts.Cluster.ConnectRetries != 0 {
opts.Cluster.ConnectRetries = flagOpts.Cluster.ConnectRetries
}
if flagOpts.Cluster.Advertise != "" {
opts.Cluster.Advertise = flagOpts.Cluster.Advertise
}
if flagOpts.RoutesStr != "" {
mergeRoutes(&opts, flagOpts)
}
return &opts
} | go | func MergeOptions(fileOpts, flagOpts *Options) *Options {
if fileOpts == nil {
return flagOpts
}
if flagOpts == nil {
return fileOpts
}
// Merge the two, flagOpts override
opts := *fileOpts
if flagOpts.Port != 0 {
opts.Port = flagOpts.Port
}
if flagOpts.Host != "" {
opts.Host = flagOpts.Host
}
if flagOpts.ClientAdvertise != "" {
opts.ClientAdvertise = flagOpts.ClientAdvertise
}
if flagOpts.Username != "" {
opts.Username = flagOpts.Username
}
if flagOpts.Password != "" {
opts.Password = flagOpts.Password
}
if flagOpts.Authorization != "" {
opts.Authorization = flagOpts.Authorization
}
if flagOpts.HTTPPort != 0 {
opts.HTTPPort = flagOpts.HTTPPort
}
if flagOpts.Debug {
opts.Debug = true
}
if flagOpts.Trace {
opts.Trace = true
}
if flagOpts.Logtime {
opts.Logtime = true
}
if flagOpts.LogFile != "" {
opts.LogFile = flagOpts.LogFile
}
if flagOpts.PidFile != "" {
opts.PidFile = flagOpts.PidFile
}
if flagOpts.PortsFileDir != "" {
opts.PortsFileDir = flagOpts.PortsFileDir
}
if flagOpts.ProfPort != 0 {
opts.ProfPort = flagOpts.ProfPort
}
if flagOpts.Cluster.ListenStr != "" {
opts.Cluster.ListenStr = flagOpts.Cluster.ListenStr
}
if flagOpts.Cluster.NoAdvertise {
opts.Cluster.NoAdvertise = true
}
if flagOpts.Cluster.ConnectRetries != 0 {
opts.Cluster.ConnectRetries = flagOpts.Cluster.ConnectRetries
}
if flagOpts.Cluster.Advertise != "" {
opts.Cluster.Advertise = flagOpts.Cluster.Advertise
}
if flagOpts.RoutesStr != "" {
mergeRoutes(&opts, flagOpts)
}
return &opts
} | [
"func",
"MergeOptions",
"(",
"fileOpts",
",",
"flagOpts",
"*",
"Options",
")",
"*",
"Options",
"{",
"if",
"fileOpts",
"==",
"nil",
"{",
"return",
"flagOpts",
"\n",
"}",
"\n",
"if",
"flagOpts",
"==",
"nil",
"{",
"return",
"fileOpts",
"\n",
"}",
"\n",
"// Merge the two, flagOpts override",
"opts",
":=",
"*",
"fileOpts",
"\n\n",
"if",
"flagOpts",
".",
"Port",
"!=",
"0",
"{",
"opts",
".",
"Port",
"=",
"flagOpts",
".",
"Port",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Host",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"Host",
"=",
"flagOpts",
".",
"Host",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"ClientAdvertise",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"ClientAdvertise",
"=",
"flagOpts",
".",
"ClientAdvertise",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Username",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"Username",
"=",
"flagOpts",
".",
"Username",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Password",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"Password",
"=",
"flagOpts",
".",
"Password",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Authorization",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"Authorization",
"=",
"flagOpts",
".",
"Authorization",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"HTTPPort",
"!=",
"0",
"{",
"opts",
".",
"HTTPPort",
"=",
"flagOpts",
".",
"HTTPPort",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Debug",
"{",
"opts",
".",
"Debug",
"=",
"true",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Trace",
"{",
"opts",
".",
"Trace",
"=",
"true",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Logtime",
"{",
"opts",
".",
"Logtime",
"=",
"true",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"LogFile",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"LogFile",
"=",
"flagOpts",
".",
"LogFile",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"PidFile",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"PidFile",
"=",
"flagOpts",
".",
"PidFile",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"PortsFileDir",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"PortsFileDir",
"=",
"flagOpts",
".",
"PortsFileDir",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"ProfPort",
"!=",
"0",
"{",
"opts",
".",
"ProfPort",
"=",
"flagOpts",
".",
"ProfPort",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Cluster",
".",
"ListenStr",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"Cluster",
".",
"ListenStr",
"=",
"flagOpts",
".",
"Cluster",
".",
"ListenStr",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Cluster",
".",
"NoAdvertise",
"{",
"opts",
".",
"Cluster",
".",
"NoAdvertise",
"=",
"true",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Cluster",
".",
"ConnectRetries",
"!=",
"0",
"{",
"opts",
".",
"Cluster",
".",
"ConnectRetries",
"=",
"flagOpts",
".",
"Cluster",
".",
"ConnectRetries",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"Cluster",
".",
"Advertise",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"Cluster",
".",
"Advertise",
"=",
"flagOpts",
".",
"Cluster",
".",
"Advertise",
"\n",
"}",
"\n",
"if",
"flagOpts",
".",
"RoutesStr",
"!=",
"\"",
"\"",
"{",
"mergeRoutes",
"(",
"&",
"opts",
",",
"flagOpts",
")",
"\n",
"}",
"\n",
"return",
"&",
"opts",
"\n",
"}"
] | // MergeOptions will merge two options giving preference to the flagOpts
// if the item is present. | [
"MergeOptions",
"will",
"merge",
"two",
"options",
"giving",
"preference",
"to",
"the",
"flagOpts",
"if",
"the",
"item",
"is",
"present",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L2152-L2220 |
164,055 | nats-io/gnatsd | server/opts.go | RoutesFromStr | func RoutesFromStr(routesStr string) []*url.URL {
routes := strings.Split(routesStr, ",")
if len(routes) == 0 {
return nil
}
routeUrls := []*url.URL{}
for _, r := range routes {
r = strings.TrimSpace(r)
u, _ := url.Parse(r)
routeUrls = append(routeUrls, u)
}
return routeUrls
} | go | func RoutesFromStr(routesStr string) []*url.URL {
routes := strings.Split(routesStr, ",")
if len(routes) == 0 {
return nil
}
routeUrls := []*url.URL{}
for _, r := range routes {
r = strings.TrimSpace(r)
u, _ := url.Parse(r)
routeUrls = append(routeUrls, u)
}
return routeUrls
} | [
"func",
"RoutesFromStr",
"(",
"routesStr",
"string",
")",
"[",
"]",
"*",
"url",
".",
"URL",
"{",
"routes",
":=",
"strings",
".",
"Split",
"(",
"routesStr",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"routes",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"routeUrls",
":=",
"[",
"]",
"*",
"url",
".",
"URL",
"{",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"routes",
"{",
"r",
"=",
"strings",
".",
"TrimSpace",
"(",
"r",
")",
"\n",
"u",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"r",
")",
"\n",
"routeUrls",
"=",
"append",
"(",
"routeUrls",
",",
"u",
")",
"\n",
"}",
"\n",
"return",
"routeUrls",
"\n",
"}"
] | // RoutesFromStr parses route URLs from a string | [
"RoutesFromStr",
"parses",
"route",
"URLs",
"from",
"a",
"string"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L2223-L2235 |
164,056 | nats-io/gnatsd | server/opts.go | mergeRoutes | func mergeRoutes(opts, flagOpts *Options) {
routeUrls := RoutesFromStr(flagOpts.RoutesStr)
if routeUrls == nil {
return
}
opts.Routes = routeUrls
opts.RoutesStr = flagOpts.RoutesStr
} | go | func mergeRoutes(opts, flagOpts *Options) {
routeUrls := RoutesFromStr(flagOpts.RoutesStr)
if routeUrls == nil {
return
}
opts.Routes = routeUrls
opts.RoutesStr = flagOpts.RoutesStr
} | [
"func",
"mergeRoutes",
"(",
"opts",
",",
"flagOpts",
"*",
"Options",
")",
"{",
"routeUrls",
":=",
"RoutesFromStr",
"(",
"flagOpts",
".",
"RoutesStr",
")",
"\n",
"if",
"routeUrls",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"opts",
".",
"Routes",
"=",
"routeUrls",
"\n",
"opts",
".",
"RoutesStr",
"=",
"flagOpts",
".",
"RoutesStr",
"\n",
"}"
] | // This will merge the flag routes and override anything that was present. | [
"This",
"will",
"merge",
"the",
"flag",
"routes",
"and",
"override",
"anything",
"that",
"was",
"present",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L2238-L2245 |
164,057 | nats-io/gnatsd | server/opts.go | RemoveSelfReference | func RemoveSelfReference(clusterPort int, routes []*url.URL) ([]*url.URL, error) {
var cleanRoutes []*url.URL
cport := strconv.Itoa(clusterPort)
selfIPs, err := getInterfaceIPs()
if err != nil {
return nil, err
}
for _, r := range routes {
host, port, err := net.SplitHostPort(r.Host)
if err != nil {
return nil, err
}
ipList, err := getURLIP(host)
if err != nil {
return nil, err
}
if cport == port && isIPInList(selfIPs, ipList) {
continue
}
cleanRoutes = append(cleanRoutes, r)
}
return cleanRoutes, nil
} | go | func RemoveSelfReference(clusterPort int, routes []*url.URL) ([]*url.URL, error) {
var cleanRoutes []*url.URL
cport := strconv.Itoa(clusterPort)
selfIPs, err := getInterfaceIPs()
if err != nil {
return nil, err
}
for _, r := range routes {
host, port, err := net.SplitHostPort(r.Host)
if err != nil {
return nil, err
}
ipList, err := getURLIP(host)
if err != nil {
return nil, err
}
if cport == port && isIPInList(selfIPs, ipList) {
continue
}
cleanRoutes = append(cleanRoutes, r)
}
return cleanRoutes, nil
} | [
"func",
"RemoveSelfReference",
"(",
"clusterPort",
"int",
",",
"routes",
"[",
"]",
"*",
"url",
".",
"URL",
")",
"(",
"[",
"]",
"*",
"url",
".",
"URL",
",",
"error",
")",
"{",
"var",
"cleanRoutes",
"[",
"]",
"*",
"url",
".",
"URL",
"\n",
"cport",
":=",
"strconv",
".",
"Itoa",
"(",
"clusterPort",
")",
"\n\n",
"selfIPs",
",",
"err",
":=",
"getInterfaceIPs",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"routes",
"{",
"host",
",",
"port",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"r",
".",
"Host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"ipList",
",",
"err",
":=",
"getURLIP",
"(",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"cport",
"==",
"port",
"&&",
"isIPInList",
"(",
"selfIPs",
",",
"ipList",
")",
"{",
"continue",
"\n",
"}",
"\n",
"cleanRoutes",
"=",
"append",
"(",
"cleanRoutes",
",",
"r",
")",
"\n",
"}",
"\n\n",
"return",
"cleanRoutes",
",",
"nil",
"\n",
"}"
] | // RemoveSelfReference removes this server from an array of routes | [
"RemoveSelfReference",
"removes",
"this",
"server",
"from",
"an",
"array",
"of",
"routes"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L2248-L2273 |
164,058 | nats-io/gnatsd | server/opts.go | overrideTLS | func overrideTLS(opts *Options) error {
if opts.TLSCert == "" {
return errors.New("TLS Server certificate must be present and valid")
}
if opts.TLSKey == "" {
return errors.New("TLS Server private key must be present and valid")
}
tc := TLSConfigOpts{}
tc.CertFile = opts.TLSCert
tc.KeyFile = opts.TLSKey
tc.CaFile = opts.TLSCaCert
tc.Verify = opts.TLSVerify
var err error
opts.TLSConfig, err = GenTLSConfig(&tc)
return err
} | go | func overrideTLS(opts *Options) error {
if opts.TLSCert == "" {
return errors.New("TLS Server certificate must be present and valid")
}
if opts.TLSKey == "" {
return errors.New("TLS Server private key must be present and valid")
}
tc := TLSConfigOpts{}
tc.CertFile = opts.TLSCert
tc.KeyFile = opts.TLSKey
tc.CaFile = opts.TLSCaCert
tc.Verify = opts.TLSVerify
var err error
opts.TLSConfig, err = GenTLSConfig(&tc)
return err
} | [
"func",
"overrideTLS",
"(",
"opts",
"*",
"Options",
")",
"error",
"{",
"if",
"opts",
".",
"TLSCert",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"opts",
".",
"TLSKey",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"tc",
":=",
"TLSConfigOpts",
"{",
"}",
"\n",
"tc",
".",
"CertFile",
"=",
"opts",
".",
"TLSCert",
"\n",
"tc",
".",
"KeyFile",
"=",
"opts",
".",
"TLSKey",
"\n",
"tc",
".",
"CaFile",
"=",
"opts",
".",
"TLSCaCert",
"\n",
"tc",
".",
"Verify",
"=",
"opts",
".",
"TLSVerify",
"\n\n",
"var",
"err",
"error",
"\n",
"opts",
".",
"TLSConfig",
",",
"err",
"=",
"GenTLSConfig",
"(",
"&",
"tc",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // overrideTLS is called when at least "-tls=true" has been set. | [
"overrideTLS",
"is",
"called",
"when",
"at",
"least",
"-",
"tls",
"=",
"true",
"has",
"been",
"set",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/opts.go#L2656-L2673 |
164,059 | nats-io/gnatsd | server/monitor_sort_opts.go | IsValid | func (s SortOpt) IsValid() bool {
switch s {
case "", ByCid, ByStart, BySubs, ByPending, ByOutMsgs, ByInMsgs, ByOutBytes, ByInBytes, ByLast, ByIdle, ByUptime, ByStop, ByReason:
return true
default:
return false
}
} | go | func (s SortOpt) IsValid() bool {
switch s {
case "", ByCid, ByStart, BySubs, ByPending, ByOutMsgs, ByInMsgs, ByOutBytes, ByInBytes, ByLast, ByIdle, ByUptime, ByStop, ByReason:
return true
default:
return false
}
} | [
"func",
"(",
"s",
"SortOpt",
")",
"IsValid",
"(",
")",
"bool",
"{",
"switch",
"s",
"{",
"case",
"\"",
"\"",
",",
"ByCid",
",",
"ByStart",
",",
"BySubs",
",",
"ByPending",
",",
"ByOutMsgs",
",",
"ByInMsgs",
",",
"ByOutBytes",
",",
"ByInBytes",
",",
"ByLast",
",",
"ByIdle",
",",
"ByUptime",
",",
"ByStop",
",",
"ByReason",
":",
"return",
"true",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // IsValid determines if a sort option is valid | [
"IsValid",
"determines",
"if",
"a",
"sort",
"option",
"is",
"valid"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/monitor_sort_opts.go#L140-L147 |
164,060 | nats-io/gnatsd | server/parser.go | clonePubArg | func (c *client) clonePubArg() {
// Just copy and re-process original arg buffer.
c.argBuf = c.scratch[:0]
c.argBuf = append(c.argBuf, c.pa.arg...)
// This is a routed msg
if c.pa.account != nil {
c.processRoutedMsgArgs(false, c.argBuf)
} else {
c.processPub(false, c.argBuf)
}
} | go | func (c *client) clonePubArg() {
// Just copy and re-process original arg buffer.
c.argBuf = c.scratch[:0]
c.argBuf = append(c.argBuf, c.pa.arg...)
// This is a routed msg
if c.pa.account != nil {
c.processRoutedMsgArgs(false, c.argBuf)
} else {
c.processPub(false, c.argBuf)
}
} | [
"func",
"(",
"c",
"*",
"client",
")",
"clonePubArg",
"(",
")",
"{",
"// Just copy and re-process original arg buffer.",
"c",
".",
"argBuf",
"=",
"c",
".",
"scratch",
"[",
":",
"0",
"]",
"\n",
"c",
".",
"argBuf",
"=",
"append",
"(",
"c",
".",
"argBuf",
",",
"c",
".",
"pa",
".",
"arg",
"...",
")",
"\n\n",
"// This is a routed msg",
"if",
"c",
".",
"pa",
".",
"account",
"!=",
"nil",
"{",
"c",
".",
"processRoutedMsgArgs",
"(",
"false",
",",
"c",
".",
"argBuf",
")",
"\n",
"}",
"else",
"{",
"c",
".",
"processPub",
"(",
"false",
",",
"c",
".",
"argBuf",
")",
"\n",
"}",
"\n",
"}"
] | // clonePubArg is used when the split buffer scenario has the pubArg in the existing read buffer, but
// we need to hold onto it into the next read. | [
"clonePubArg",
"is",
"used",
"when",
"the",
"split",
"buffer",
"scenario",
"has",
"the",
"pubArg",
"in",
"the",
"existing",
"read",
"buffer",
"but",
"we",
"need",
"to",
"hold",
"onto",
"it",
"into",
"the",
"next",
"read",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/parser.go#L911-L922 |
164,061 | nats-io/gnatsd | server/server.go | NewServer | func NewServer(opts *Options) (*Server, error) {
setBaselineOptions(opts)
// Process TLS options, including whether we require client certificates.
tlsReq := opts.TLSConfig != nil
verify := (tlsReq && opts.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert)
// Created server's nkey identity.
kp, _ := nkeys.CreateServer()
pub, _ := kp.PublicKey()
// Validate some options. This is here because we cannot assume that
// server will always be started with configuration parsing (that could
// report issues). Its options can be (incorrectly) set by hand when
// server is embedded. If there is an error, return nil.
if err := validateOptions(opts); err != nil {
return nil, err
}
info := Info{
ID: pub,
Version: VERSION,
Proto: PROTO,
GitCommit: gitCommit,
GoVersion: runtime.Version(),
Host: opts.Host,
Port: opts.Port,
AuthRequired: false,
TLSRequired: tlsReq,
TLSVerify: verify,
MaxPayload: opts.MaxPayload,
}
now := time.Now()
s := &Server{
kp: kp,
configFile: opts.ConfigFile,
info: info,
prand: rand.New(rand.NewSource(time.Now().UnixNano())),
opts: opts,
done: make(chan bool, 1),
start: now,
configTime: now,
}
// Trusted root operator keys.
if !s.processTrustedKeys() {
return nil, fmt.Errorf("Error processing trusted operator keys")
}
s.mu.Lock()
defer s.mu.Unlock()
// Ensure that non-exported options (used in tests) are properly set.
s.setLeafNodeNonExportedOptions()
// Used internally for quick look-ups.
s.clientConnectURLsMap = make(map[string]struct{})
// Call this even if there is no gateway defined. It will
// initialize the structure so we don't have to check for
// it to be nil or not in various places in the code.
gws, err := newGateway(opts)
if err != nil {
return nil, err
}
s.gateway = gws
if s.gateway.enabled {
s.info.Cluster = s.getGatewayName()
}
// This is normally done in the AcceptLoop, once the
// listener has been created (possibly with random port),
// but since some tests may expect the INFO to be properly
// set after New(), let's do it now.
s.setInfoHostPortAndGenerateJSON()
// For tracking clients
s.clients = make(map[uint64]*client)
// For tracking closed clients.
s.closed = newClosedRingBuffer(opts.MaxClosedClients)
// For tracking connections that are not yet registered
// in s.routes, but for which readLoop has started.
s.grTmpClients = make(map[uint64]*client)
// For tracking routes and their remote ids
s.routes = make(map[uint64]*client)
s.remotes = make(map[string]*client)
// For tracking leaf nodes.
s.leafs = make(map[uint64]*client)
// Used to kick out all go routines possibly waiting on server
// to shutdown.
s.quitCh = make(chan struct{})
// For tracking accounts
if err := s.configureAccounts(); err != nil {
return nil, err
}
// Used to setup Authorization.
s.configureAuthorization()
// Start signal handler
s.handleSignals()
return s, nil
} | go | func NewServer(opts *Options) (*Server, error) {
setBaselineOptions(opts)
// Process TLS options, including whether we require client certificates.
tlsReq := opts.TLSConfig != nil
verify := (tlsReq && opts.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert)
// Created server's nkey identity.
kp, _ := nkeys.CreateServer()
pub, _ := kp.PublicKey()
// Validate some options. This is here because we cannot assume that
// server will always be started with configuration parsing (that could
// report issues). Its options can be (incorrectly) set by hand when
// server is embedded. If there is an error, return nil.
if err := validateOptions(opts); err != nil {
return nil, err
}
info := Info{
ID: pub,
Version: VERSION,
Proto: PROTO,
GitCommit: gitCommit,
GoVersion: runtime.Version(),
Host: opts.Host,
Port: opts.Port,
AuthRequired: false,
TLSRequired: tlsReq,
TLSVerify: verify,
MaxPayload: opts.MaxPayload,
}
now := time.Now()
s := &Server{
kp: kp,
configFile: opts.ConfigFile,
info: info,
prand: rand.New(rand.NewSource(time.Now().UnixNano())),
opts: opts,
done: make(chan bool, 1),
start: now,
configTime: now,
}
// Trusted root operator keys.
if !s.processTrustedKeys() {
return nil, fmt.Errorf("Error processing trusted operator keys")
}
s.mu.Lock()
defer s.mu.Unlock()
// Ensure that non-exported options (used in tests) are properly set.
s.setLeafNodeNonExportedOptions()
// Used internally for quick look-ups.
s.clientConnectURLsMap = make(map[string]struct{})
// Call this even if there is no gateway defined. It will
// initialize the structure so we don't have to check for
// it to be nil or not in various places in the code.
gws, err := newGateway(opts)
if err != nil {
return nil, err
}
s.gateway = gws
if s.gateway.enabled {
s.info.Cluster = s.getGatewayName()
}
// This is normally done in the AcceptLoop, once the
// listener has been created (possibly with random port),
// but since some tests may expect the INFO to be properly
// set after New(), let's do it now.
s.setInfoHostPortAndGenerateJSON()
// For tracking clients
s.clients = make(map[uint64]*client)
// For tracking closed clients.
s.closed = newClosedRingBuffer(opts.MaxClosedClients)
// For tracking connections that are not yet registered
// in s.routes, but for which readLoop has started.
s.grTmpClients = make(map[uint64]*client)
// For tracking routes and their remote ids
s.routes = make(map[uint64]*client)
s.remotes = make(map[string]*client)
// For tracking leaf nodes.
s.leafs = make(map[uint64]*client)
// Used to kick out all go routines possibly waiting on server
// to shutdown.
s.quitCh = make(chan struct{})
// For tracking accounts
if err := s.configureAccounts(); err != nil {
return nil, err
}
// Used to setup Authorization.
s.configureAuthorization()
// Start signal handler
s.handleSignals()
return s, nil
} | [
"func",
"NewServer",
"(",
"opts",
"*",
"Options",
")",
"(",
"*",
"Server",
",",
"error",
")",
"{",
"setBaselineOptions",
"(",
"opts",
")",
"\n\n",
"// Process TLS options, including whether we require client certificates.",
"tlsReq",
":=",
"opts",
".",
"TLSConfig",
"!=",
"nil",
"\n",
"verify",
":=",
"(",
"tlsReq",
"&&",
"opts",
".",
"TLSConfig",
".",
"ClientAuth",
"==",
"tls",
".",
"RequireAndVerifyClientCert",
")",
"\n\n",
"// Created server's nkey identity.",
"kp",
",",
"_",
":=",
"nkeys",
".",
"CreateServer",
"(",
")",
"\n",
"pub",
",",
"_",
":=",
"kp",
".",
"PublicKey",
"(",
")",
"\n\n",
"// Validate some options. This is here because we cannot assume that",
"// server will always be started with configuration parsing (that could",
"// report issues). Its options can be (incorrectly) set by hand when",
"// server is embedded. If there is an error, return nil.",
"if",
"err",
":=",
"validateOptions",
"(",
"opts",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"info",
":=",
"Info",
"{",
"ID",
":",
"pub",
",",
"Version",
":",
"VERSION",
",",
"Proto",
":",
"PROTO",
",",
"GitCommit",
":",
"gitCommit",
",",
"GoVersion",
":",
"runtime",
".",
"Version",
"(",
")",
",",
"Host",
":",
"opts",
".",
"Host",
",",
"Port",
":",
"opts",
".",
"Port",
",",
"AuthRequired",
":",
"false",
",",
"TLSRequired",
":",
"tlsReq",
",",
"TLSVerify",
":",
"verify",
",",
"MaxPayload",
":",
"opts",
".",
"MaxPayload",
",",
"}",
"\n\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"s",
":=",
"&",
"Server",
"{",
"kp",
":",
"kp",
",",
"configFile",
":",
"opts",
".",
"ConfigFile",
",",
"info",
":",
"info",
",",
"prand",
":",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
")",
",",
"opts",
":",
"opts",
",",
"done",
":",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
",",
"start",
":",
"now",
",",
"configTime",
":",
"now",
",",
"}",
"\n\n",
"// Trusted root operator keys.",
"if",
"!",
"s",
".",
"processTrustedKeys",
"(",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Ensure that non-exported options (used in tests) are properly set.",
"s",
".",
"setLeafNodeNonExportedOptions",
"(",
")",
"\n\n",
"// Used internally for quick look-ups.",
"s",
".",
"clientConnectURLsMap",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n\n",
"// Call this even if there is no gateway defined. It will",
"// initialize the structure so we don't have to check for",
"// it to be nil or not in various places in the code.",
"gws",
",",
"err",
":=",
"newGateway",
"(",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"s",
".",
"gateway",
"=",
"gws",
"\n\n",
"if",
"s",
".",
"gateway",
".",
"enabled",
"{",
"s",
".",
"info",
".",
"Cluster",
"=",
"s",
".",
"getGatewayName",
"(",
")",
"\n",
"}",
"\n\n",
"// This is normally done in the AcceptLoop, once the",
"// listener has been created (possibly with random port),",
"// but since some tests may expect the INFO to be properly",
"// set after New(), let's do it now.",
"s",
".",
"setInfoHostPortAndGenerateJSON",
"(",
")",
"\n\n",
"// For tracking clients",
"s",
".",
"clients",
"=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"*",
"client",
")",
"\n\n",
"// For tracking closed clients.",
"s",
".",
"closed",
"=",
"newClosedRingBuffer",
"(",
"opts",
".",
"MaxClosedClients",
")",
"\n\n",
"// For tracking connections that are not yet registered",
"// in s.routes, but for which readLoop has started.",
"s",
".",
"grTmpClients",
"=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"*",
"client",
")",
"\n\n",
"// For tracking routes and their remote ids",
"s",
".",
"routes",
"=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"*",
"client",
")",
"\n",
"s",
".",
"remotes",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"client",
")",
"\n\n",
"// For tracking leaf nodes.",
"s",
".",
"leafs",
"=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"*",
"client",
")",
"\n\n",
"// Used to kick out all go routines possibly waiting on server",
"// to shutdown.",
"s",
".",
"quitCh",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n\n",
"// For tracking accounts",
"if",
"err",
":=",
"s",
".",
"configureAccounts",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Used to setup Authorization.",
"s",
".",
"configureAuthorization",
"(",
")",
"\n\n",
"// Start signal handler",
"s",
".",
"handleSignals",
"(",
")",
"\n\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // NewServer will setup a new server struct after parsing the options.
// Could return an error if options can not be validated. | [
"NewServer",
"will",
"setup",
"a",
"new",
"server",
"struct",
"after",
"parsing",
"the",
"options",
".",
"Could",
"return",
"an",
"error",
"if",
"options",
"can",
"not",
"be",
"validated",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L189-L300 |
164,062 | nats-io/gnatsd | server/server.go | configureAccounts | func (s *Server) configureAccounts() error {
// Create global account.
if s.gacc == nil {
s.gacc = NewAccount(globalAccountName)
s.registerAccount(s.gacc)
}
opts := s.opts
// Check opts and walk through them. We need to copy them here
// so that we do not keep a real one sitting in the options.
for _, acc := range s.opts.Accounts {
a := acc.shallowCopy()
acc.sl = nil
acc.clients = nil
s.registerAccount(a)
}
// Now that we have this we need to remap any referenced accounts in
// import or export maps to the new ones.
swapApproved := func(ea *exportAuth) {
if ea == nil {
return
}
for sub, a := range ea.approved {
var acc *Account
if v, ok := s.accounts.Load(a.Name); ok {
acc = v.(*Account)
}
ea.approved[sub] = acc
}
}
s.accounts.Range(func(k, v interface{}) bool {
acc := v.(*Account)
// Exports
for _, ea := range acc.exports.streams {
swapApproved(ea)
}
for _, ea := range acc.exports.services {
swapApproved(ea)
}
// Imports
for _, si := range acc.imports.streams {
if v, ok := s.accounts.Load(si.acc.Name); ok {
si.acc = v.(*Account)
}
}
for _, si := range acc.imports.services {
if v, ok := s.accounts.Load(si.acc.Name); ok {
si.acc = v.(*Account)
}
}
return true
})
// Check for configured account resolvers.
if opts.AccountResolver != nil {
s.accResolver = opts.AccountResolver
if len(opts.resolverPreloads) > 0 {
if _, ok := s.accResolver.(*MemAccResolver); !ok {
return fmt.Errorf("resolver preloads only available for MemAccResolver")
}
for k, v := range opts.resolverPreloads {
if _, _, err := s.verifyAccountClaims(v); err != nil {
return fmt.Errorf("preloaded Account: %v", err)
}
s.accResolver.Store(k, v)
}
}
}
// Set the system account if it was configured.
if opts.SystemAccount != _EMPTY_ {
// Lock is held entering this function, so release to call lookupAccount.
s.mu.Unlock()
_, err := s.lookupAccount(opts.SystemAccount)
s.mu.Lock()
if err != nil {
return fmt.Errorf("error resolving system account: %v", err)
}
}
return nil
} | go | func (s *Server) configureAccounts() error {
// Create global account.
if s.gacc == nil {
s.gacc = NewAccount(globalAccountName)
s.registerAccount(s.gacc)
}
opts := s.opts
// Check opts and walk through them. We need to copy them here
// so that we do not keep a real one sitting in the options.
for _, acc := range s.opts.Accounts {
a := acc.shallowCopy()
acc.sl = nil
acc.clients = nil
s.registerAccount(a)
}
// Now that we have this we need to remap any referenced accounts in
// import or export maps to the new ones.
swapApproved := func(ea *exportAuth) {
if ea == nil {
return
}
for sub, a := range ea.approved {
var acc *Account
if v, ok := s.accounts.Load(a.Name); ok {
acc = v.(*Account)
}
ea.approved[sub] = acc
}
}
s.accounts.Range(func(k, v interface{}) bool {
acc := v.(*Account)
// Exports
for _, ea := range acc.exports.streams {
swapApproved(ea)
}
for _, ea := range acc.exports.services {
swapApproved(ea)
}
// Imports
for _, si := range acc.imports.streams {
if v, ok := s.accounts.Load(si.acc.Name); ok {
si.acc = v.(*Account)
}
}
for _, si := range acc.imports.services {
if v, ok := s.accounts.Load(si.acc.Name); ok {
si.acc = v.(*Account)
}
}
return true
})
// Check for configured account resolvers.
if opts.AccountResolver != nil {
s.accResolver = opts.AccountResolver
if len(opts.resolverPreloads) > 0 {
if _, ok := s.accResolver.(*MemAccResolver); !ok {
return fmt.Errorf("resolver preloads only available for MemAccResolver")
}
for k, v := range opts.resolverPreloads {
if _, _, err := s.verifyAccountClaims(v); err != nil {
return fmt.Errorf("preloaded Account: %v", err)
}
s.accResolver.Store(k, v)
}
}
}
// Set the system account if it was configured.
if opts.SystemAccount != _EMPTY_ {
// Lock is held entering this function, so release to call lookupAccount.
s.mu.Unlock()
_, err := s.lookupAccount(opts.SystemAccount)
s.mu.Lock()
if err != nil {
return fmt.Errorf("error resolving system account: %v", err)
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"configureAccounts",
"(",
")",
"error",
"{",
"// Create global account.",
"if",
"s",
".",
"gacc",
"==",
"nil",
"{",
"s",
".",
"gacc",
"=",
"NewAccount",
"(",
"globalAccountName",
")",
"\n",
"s",
".",
"registerAccount",
"(",
"s",
".",
"gacc",
")",
"\n",
"}",
"\n\n",
"opts",
":=",
"s",
".",
"opts",
"\n\n",
"// Check opts and walk through them. We need to copy them here",
"// so that we do not keep a real one sitting in the options.",
"for",
"_",
",",
"acc",
":=",
"range",
"s",
".",
"opts",
".",
"Accounts",
"{",
"a",
":=",
"acc",
".",
"shallowCopy",
"(",
")",
"\n",
"acc",
".",
"sl",
"=",
"nil",
"\n",
"acc",
".",
"clients",
"=",
"nil",
"\n",
"s",
".",
"registerAccount",
"(",
"a",
")",
"\n",
"}",
"\n\n",
"// Now that we have this we need to remap any referenced accounts in",
"// import or export maps to the new ones.",
"swapApproved",
":=",
"func",
"(",
"ea",
"*",
"exportAuth",
")",
"{",
"if",
"ea",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"for",
"sub",
",",
"a",
":=",
"range",
"ea",
".",
"approved",
"{",
"var",
"acc",
"*",
"Account",
"\n",
"if",
"v",
",",
"ok",
":=",
"s",
".",
"accounts",
".",
"Load",
"(",
"a",
".",
"Name",
")",
";",
"ok",
"{",
"acc",
"=",
"v",
".",
"(",
"*",
"Account",
")",
"\n",
"}",
"\n",
"ea",
".",
"approved",
"[",
"sub",
"]",
"=",
"acc",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"accounts",
".",
"Range",
"(",
"func",
"(",
"k",
",",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"acc",
":=",
"v",
".",
"(",
"*",
"Account",
")",
"\n",
"// Exports",
"for",
"_",
",",
"ea",
":=",
"range",
"acc",
".",
"exports",
".",
"streams",
"{",
"swapApproved",
"(",
"ea",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"ea",
":=",
"range",
"acc",
".",
"exports",
".",
"services",
"{",
"swapApproved",
"(",
"ea",
")",
"\n",
"}",
"\n",
"// Imports",
"for",
"_",
",",
"si",
":=",
"range",
"acc",
".",
"imports",
".",
"streams",
"{",
"if",
"v",
",",
"ok",
":=",
"s",
".",
"accounts",
".",
"Load",
"(",
"si",
".",
"acc",
".",
"Name",
")",
";",
"ok",
"{",
"si",
".",
"acc",
"=",
"v",
".",
"(",
"*",
"Account",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"si",
":=",
"range",
"acc",
".",
"imports",
".",
"services",
"{",
"if",
"v",
",",
"ok",
":=",
"s",
".",
"accounts",
".",
"Load",
"(",
"si",
".",
"acc",
".",
"Name",
")",
";",
"ok",
"{",
"si",
".",
"acc",
"=",
"v",
".",
"(",
"*",
"Account",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n\n",
"// Check for configured account resolvers.",
"if",
"opts",
".",
"AccountResolver",
"!=",
"nil",
"{",
"s",
".",
"accResolver",
"=",
"opts",
".",
"AccountResolver",
"\n",
"if",
"len",
"(",
"opts",
".",
"resolverPreloads",
")",
">",
"0",
"{",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"accResolver",
".",
"(",
"*",
"MemAccResolver",
")",
";",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"opts",
".",
"resolverPreloads",
"{",
"if",
"_",
",",
"_",
",",
"err",
":=",
"s",
".",
"verifyAccountClaims",
"(",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"s",
".",
"accResolver",
".",
"Store",
"(",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// Set the system account if it was configured.",
"if",
"opts",
".",
"SystemAccount",
"!=",
"_EMPTY_",
"{",
"// Lock is held entering this function, so release to call lookupAccount.",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"lookupAccount",
"(",
"opts",
".",
"SystemAccount",
")",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Used to setup Accounts. | [
"Used",
"to",
"setup",
"Accounts",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L343-L425 |
164,063 | nats-io/gnatsd | server/server.go | isTrustedIssuer | func (s *Server) isTrustedIssuer(issuer string) bool {
s.mu.Lock()
defer s.mu.Unlock()
// If we are not running in trusted mode and there is no issuer, that is ok.
if len(s.trustedKeys) == 0 && issuer == "" {
return true
}
for _, tk := range s.trustedKeys {
if tk == issuer {
return true
}
}
return false
} | go | func (s *Server) isTrustedIssuer(issuer string) bool {
s.mu.Lock()
defer s.mu.Unlock()
// If we are not running in trusted mode and there is no issuer, that is ok.
if len(s.trustedKeys) == 0 && issuer == "" {
return true
}
for _, tk := range s.trustedKeys {
if tk == issuer {
return true
}
}
return false
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"isTrustedIssuer",
"(",
"issuer",
"string",
")",
"bool",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"// If we are not running in trusted mode and there is no issuer, that is ok.",
"if",
"len",
"(",
"s",
".",
"trustedKeys",
")",
"==",
"0",
"&&",
"issuer",
"==",
"\"",
"\"",
"{",
"return",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"tk",
":=",
"range",
"s",
".",
"trustedKeys",
"{",
"if",
"tk",
"==",
"issuer",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // isTrustedIssuer will check that the issuer is a trusted public key.
// This is used to make sure an account was signed by a trusted operator. | [
"isTrustedIssuer",
"will",
"check",
"that",
"the",
"issuer",
"is",
"a",
"trusted",
"public",
"key",
".",
"This",
"is",
"used",
"to",
"make",
"sure",
"an",
"account",
"was",
"signed",
"by",
"a",
"trusted",
"operator",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L440-L453 |
164,064 | nats-io/gnatsd | server/server.go | processTrustedKeys | func (s *Server) processTrustedKeys() bool {
if trustedKeys != "" && !s.initStampedTrustedKeys() {
return false
} else if s.opts.TrustedKeys != nil {
for _, key := range s.opts.TrustedKeys {
if !nkeys.IsValidPublicOperatorKey(key) {
return false
}
}
s.trustedKeys = s.opts.TrustedKeys
}
return true
} | go | func (s *Server) processTrustedKeys() bool {
if trustedKeys != "" && !s.initStampedTrustedKeys() {
return false
} else if s.opts.TrustedKeys != nil {
for _, key := range s.opts.TrustedKeys {
if !nkeys.IsValidPublicOperatorKey(key) {
return false
}
}
s.trustedKeys = s.opts.TrustedKeys
}
return true
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"processTrustedKeys",
"(",
")",
"bool",
"{",
"if",
"trustedKeys",
"!=",
"\"",
"\"",
"&&",
"!",
"s",
".",
"initStampedTrustedKeys",
"(",
")",
"{",
"return",
"false",
"\n",
"}",
"else",
"if",
"s",
".",
"opts",
".",
"TrustedKeys",
"!=",
"nil",
"{",
"for",
"_",
",",
"key",
":=",
"range",
"s",
".",
"opts",
".",
"TrustedKeys",
"{",
"if",
"!",
"nkeys",
".",
"IsValidPublicOperatorKey",
"(",
"key",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"trustedKeys",
"=",
"s",
".",
"opts",
".",
"TrustedKeys",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // processTrustedKeys will process binary stamped and
// options-based trusted nkeys. Returns success. | [
"processTrustedKeys",
"will",
"process",
"binary",
"stamped",
"and",
"options",
"-",
"based",
"trusted",
"nkeys",
".",
"Returns",
"success",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L457-L469 |
164,065 | nats-io/gnatsd | server/server.go | checkTrustedKeyString | func checkTrustedKeyString(keys string) []string {
tks := strings.Fields(keys)
if len(tks) == 0 {
return nil
}
// Walk all the keys and make sure they are valid.
for _, key := range tks {
if !nkeys.IsValidPublicOperatorKey(key) {
return nil
}
}
return tks
} | go | func checkTrustedKeyString(keys string) []string {
tks := strings.Fields(keys)
if len(tks) == 0 {
return nil
}
// Walk all the keys and make sure they are valid.
for _, key := range tks {
if !nkeys.IsValidPublicOperatorKey(key) {
return nil
}
}
return tks
} | [
"func",
"checkTrustedKeyString",
"(",
"keys",
"string",
")",
"[",
"]",
"string",
"{",
"tks",
":=",
"strings",
".",
"Fields",
"(",
"keys",
")",
"\n",
"if",
"len",
"(",
"tks",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"// Walk all the keys and make sure they are valid.",
"for",
"_",
",",
"key",
":=",
"range",
"tks",
"{",
"if",
"!",
"nkeys",
".",
"IsValidPublicOperatorKey",
"(",
"key",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"tks",
"\n",
"}"
] | // checkTrustedKeyString will check that the string is a valid array
// of public operator nkeys. | [
"checkTrustedKeyString",
"will",
"check",
"that",
"the",
"string",
"is",
"a",
"valid",
"array",
"of",
"public",
"operator",
"nkeys",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L473-L485 |
164,066 | nats-io/gnatsd | server/server.go | initStampedTrustedKeys | func (s *Server) initStampedTrustedKeys() bool {
// Check to see if we have an override in options, which will cause us to fail.
if len(s.opts.TrustedKeys) > 0 {
return false
}
tks := checkTrustedKeyString(trustedKeys)
if len(tks) == 0 {
return false
}
s.trustedKeys = tks
return true
} | go | func (s *Server) initStampedTrustedKeys() bool {
// Check to see if we have an override in options, which will cause us to fail.
if len(s.opts.TrustedKeys) > 0 {
return false
}
tks := checkTrustedKeyString(trustedKeys)
if len(tks) == 0 {
return false
}
s.trustedKeys = tks
return true
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"initStampedTrustedKeys",
"(",
")",
"bool",
"{",
"// Check to see if we have an override in options, which will cause us to fail.",
"if",
"len",
"(",
"s",
".",
"opts",
".",
"TrustedKeys",
")",
">",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"tks",
":=",
"checkTrustedKeyString",
"(",
"trustedKeys",
")",
"\n",
"if",
"len",
"(",
"tks",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"s",
".",
"trustedKeys",
"=",
"tks",
"\n",
"return",
"true",
"\n",
"}"
] | // initStampedTrustedKeys will check the stamped trusted keys
// and will set the server field 'trustedKeys'. Returns whether
// it succeeded or not. | [
"initStampedTrustedKeys",
"will",
"check",
"the",
"stamped",
"trusted",
"keys",
"and",
"will",
"set",
"the",
"server",
"field",
"trustedKeys",
".",
"Returns",
"whether",
"it",
"succeeded",
"or",
"not",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L490-L501 |
164,067 | nats-io/gnatsd | server/server.go | PrintAndDie | func PrintAndDie(msg string) {
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
} | go | func PrintAndDie(msg string) {
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
} | [
"func",
"PrintAndDie",
"(",
"msg",
"string",
")",
"{",
"fmt",
".",
"Fprintln",
"(",
"os",
".",
"Stderr",
",",
"msg",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // PrintAndDie is exported for access in other packages. | [
"PrintAndDie",
"is",
"exported",
"for",
"access",
"in",
"other",
"packages",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L504-L507 |
164,068 | nats-io/gnatsd | server/server.go | ProcessCommandLineArgs | func ProcessCommandLineArgs(cmd *flag.FlagSet) (showVersion bool, showHelp bool, err error) {
if len(cmd.Args()) > 0 {
arg := cmd.Args()[0]
switch strings.ToLower(arg) {
case "version":
return true, false, nil
case "help":
return false, true, nil
default:
return false, false, fmt.Errorf("unrecognized command: %q", arg)
}
}
return false, false, nil
} | go | func ProcessCommandLineArgs(cmd *flag.FlagSet) (showVersion bool, showHelp bool, err error) {
if len(cmd.Args()) > 0 {
arg := cmd.Args()[0]
switch strings.ToLower(arg) {
case "version":
return true, false, nil
case "help":
return false, true, nil
default:
return false, false, fmt.Errorf("unrecognized command: %q", arg)
}
}
return false, false, nil
} | [
"func",
"ProcessCommandLineArgs",
"(",
"cmd",
"*",
"flag",
".",
"FlagSet",
")",
"(",
"showVersion",
"bool",
",",
"showHelp",
"bool",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"cmd",
".",
"Args",
"(",
")",
")",
">",
"0",
"{",
"arg",
":=",
"cmd",
".",
"Args",
"(",
")",
"[",
"0",
"]",
"\n",
"switch",
"strings",
".",
"ToLower",
"(",
"arg",
")",
"{",
"case",
"\"",
"\"",
":",
"return",
"true",
",",
"false",
",",
"nil",
"\n",
"case",
"\"",
"\"",
":",
"return",
"false",
",",
"true",
",",
"nil",
"\n",
"default",
":",
"return",
"false",
",",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"arg",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"false",
",",
"nil",
"\n",
"}"
] | // ProcessCommandLineArgs takes the command line arguments
// validating and setting flags for handling in case any
// sub command was present. | [
"ProcessCommandLineArgs",
"takes",
"the",
"command",
"line",
"arguments",
"validating",
"and",
"setting",
"flags",
"for",
"handling",
"in",
"case",
"any",
"sub",
"command",
"was",
"present",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L518-L532 |
164,069 | nats-io/gnatsd | server/server.go | isRunning | func (s *Server) isRunning() bool {
s.mu.Lock()
running := s.running
s.mu.Unlock()
return running
} | go | func (s *Server) isRunning() bool {
s.mu.Lock()
running := s.running
s.mu.Unlock()
return running
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"isRunning",
"(",
")",
"bool",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"running",
":=",
"s",
".",
"running",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"running",
"\n",
"}"
] | // Protected check on running state | [
"Protected",
"check",
"on",
"running",
"state"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L535-L540 |
164,070 | nats-io/gnatsd | server/server.go | NewAccountsAllowed | func (s *Server) NewAccountsAllowed() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.opts.AllowNewAccounts
} | go | func (s *Server) NewAccountsAllowed() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.opts.AllowNewAccounts
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"NewAccountsAllowed",
"(",
")",
"bool",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"s",
".",
"opts",
".",
"AllowNewAccounts",
"\n",
"}"
] | // NewAccountsAllowed returns whether or not new accounts can be created on the fly. | [
"NewAccountsAllowed",
"returns",
"whether",
"or",
"not",
"new",
"accounts",
"can",
"be",
"created",
"on",
"the",
"fly",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L548-L552 |
164,071 | nats-io/gnatsd | server/server.go | numAccounts | func (s *Server) numAccounts() int {
count := 0
s.mu.Lock()
s.accounts.Range(func(k, v interface{}) bool {
count++
return true
})
s.mu.Unlock()
return count
} | go | func (s *Server) numAccounts() int {
count := 0
s.mu.Lock()
s.accounts.Range(func(k, v interface{}) bool {
count++
return true
})
s.mu.Unlock()
return count
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"numAccounts",
"(",
")",
"int",
"{",
"count",
":=",
"0",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"accounts",
".",
"Range",
"(",
"func",
"(",
"k",
",",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"count",
"++",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"count",
"\n",
"}"
] | // This should be used for testing only. Will be slow since we have to
// range over all accounts in the sync.Map to count. | [
"This",
"should",
"be",
"used",
"for",
"testing",
"only",
".",
"Will",
"be",
"slow",
"since",
"we",
"have",
"to",
"range",
"over",
"all",
"accounts",
"in",
"the",
"sync",
".",
"Map",
"to",
"count",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L577-L586 |
164,072 | nats-io/gnatsd | server/server.go | LookupOrRegisterAccount | func (s *Server) LookupOrRegisterAccount(name string) (account *Account, isNew bool) {
if v, ok := s.accounts.Load(name); ok {
return v.(*Account), false
}
s.mu.Lock()
acc := NewAccount(name)
s.registerAccount(acc)
s.mu.Unlock()
return acc, true
} | go | func (s *Server) LookupOrRegisterAccount(name string) (account *Account, isNew bool) {
if v, ok := s.accounts.Load(name); ok {
return v.(*Account), false
}
s.mu.Lock()
acc := NewAccount(name)
s.registerAccount(acc)
s.mu.Unlock()
return acc, true
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"LookupOrRegisterAccount",
"(",
"name",
"string",
")",
"(",
"account",
"*",
"Account",
",",
"isNew",
"bool",
")",
"{",
"if",
"v",
",",
"ok",
":=",
"s",
".",
"accounts",
".",
"Load",
"(",
"name",
")",
";",
"ok",
"{",
"return",
"v",
".",
"(",
"*",
"Account",
")",
",",
"false",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"acc",
":=",
"NewAccount",
"(",
"name",
")",
"\n",
"s",
".",
"registerAccount",
"(",
"acc",
")",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"acc",
",",
"true",
"\n",
"}"
] | // LookupOrRegisterAccount will return the given account if known or create a new entry. | [
"LookupOrRegisterAccount",
"will",
"return",
"the",
"given",
"account",
"if",
"known",
"or",
"create",
"a",
"new",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L589-L598 |
164,073 | nats-io/gnatsd | server/server.go | RegisterAccount | func (s *Server) RegisterAccount(name string) (*Account, error) {
if _, ok := s.accounts.Load(name); ok {
return nil, ErrAccountExists
}
s.mu.Lock()
acc := NewAccount(name)
s.registerAccount(acc)
s.mu.Unlock()
return acc, nil
} | go | func (s *Server) RegisterAccount(name string) (*Account, error) {
if _, ok := s.accounts.Load(name); ok {
return nil, ErrAccountExists
}
s.mu.Lock()
acc := NewAccount(name)
s.registerAccount(acc)
s.mu.Unlock()
return acc, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"RegisterAccount",
"(",
"name",
"string",
")",
"(",
"*",
"Account",
",",
"error",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"accounts",
".",
"Load",
"(",
"name",
")",
";",
"ok",
"{",
"return",
"nil",
",",
"ErrAccountExists",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"acc",
":=",
"NewAccount",
"(",
"name",
")",
"\n",
"s",
".",
"registerAccount",
"(",
"acc",
")",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"acc",
",",
"nil",
"\n",
"}"
] | // RegisterAccount will register an account. The account must be new
// or this call will fail. | [
"RegisterAccount",
"will",
"register",
"an",
"account",
".",
"The",
"account",
"must",
"be",
"new",
"or",
"this",
"call",
"will",
"fail",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L602-L611 |
164,074 | nats-io/gnatsd | server/server.go | SetSystemAccount | func (s *Server) SetSystemAccount(accName string) error {
if v, ok := s.accounts.Load(accName); ok {
return s.setSystemAccount(v.(*Account))
}
s.mu.Lock()
// If we are here we do not have local knowledge of this account.
// Do this one by hand to return more useful error.
ac, jwt, err := s.fetchAccountClaims(accName)
if err != nil {
s.mu.Unlock()
return err
}
acc := s.buildInternalAccount(ac)
acc.claimJWT = jwt
s.registerAccount(acc)
s.mu.Unlock()
return s.setSystemAccount(acc)
} | go | func (s *Server) SetSystemAccount(accName string) error {
if v, ok := s.accounts.Load(accName); ok {
return s.setSystemAccount(v.(*Account))
}
s.mu.Lock()
// If we are here we do not have local knowledge of this account.
// Do this one by hand to return more useful error.
ac, jwt, err := s.fetchAccountClaims(accName)
if err != nil {
s.mu.Unlock()
return err
}
acc := s.buildInternalAccount(ac)
acc.claimJWT = jwt
s.registerAccount(acc)
s.mu.Unlock()
return s.setSystemAccount(acc)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"SetSystemAccount",
"(",
"accName",
"string",
")",
"error",
"{",
"if",
"v",
",",
"ok",
":=",
"s",
".",
"accounts",
".",
"Load",
"(",
"accName",
")",
";",
"ok",
"{",
"return",
"s",
".",
"setSystemAccount",
"(",
"v",
".",
"(",
"*",
"Account",
")",
")",
"\n",
"}",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"// If we are here we do not have local knowledge of this account.",
"// Do this one by hand to return more useful error.",
"ac",
",",
"jwt",
",",
"err",
":=",
"s",
".",
"fetchAccountClaims",
"(",
"accName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"acc",
":=",
"s",
".",
"buildInternalAccount",
"(",
"ac",
")",
"\n",
"acc",
".",
"claimJWT",
"=",
"jwt",
"\n",
"s",
".",
"registerAccount",
"(",
"acc",
")",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"s",
".",
"setSystemAccount",
"(",
"acc",
")",
"\n",
"}"
] | // SetSystemAccount will set the internal system account.
// If root operators are present it will also check validity. | [
"SetSystemAccount",
"will",
"set",
"the",
"internal",
"system",
"account",
".",
"If",
"root",
"operators",
"are",
"present",
"it",
"will",
"also",
"check",
"validity",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L615-L634 |
164,075 | nats-io/gnatsd | server/server.go | SystemAccount | func (s *Server) SystemAccount() *Account {
s.mu.Lock()
defer s.mu.Unlock()
if s.sys != nil {
return s.sys.account
}
return nil
} | go | func (s *Server) SystemAccount() *Account {
s.mu.Lock()
defer s.mu.Unlock()
if s.sys != nil {
return s.sys.account
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"SystemAccount",
"(",
")",
"*",
"Account",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"s",
".",
"sys",
"!=",
"nil",
"{",
"return",
"s",
".",
"sys",
".",
"account",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SystemAccount returns the system account if set. | [
"SystemAccount",
"returns",
"the",
"system",
"account",
"if",
"set",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L637-L644 |
164,076 | nats-io/gnatsd | server/server.go | setSystemAccount | func (s *Server) setSystemAccount(acc *Account) error {
if acc == nil {
return ErrMissingAccount
}
// Don't try to fix this here.
if acc.IsExpired() {
return ErrAccountExpired
}
// If we are running with trusted keys for an operator
// make sure we check the account is legit.
if !s.isTrustedIssuer(acc.Issuer) {
return ErrAccountValidation
}
s.mu.Lock()
if s.sys != nil {
s.mu.Unlock()
return ErrAccountExists
}
s.sys = &internal{
account: acc,
client: &client{srv: s, kind: SYSTEM, opts: internalOpts, msubs: -1, mpay: -1, start: time.Now(), last: time.Now()},
seq: 1,
sid: 1,
servers: make(map[string]*serverUpdate),
subs: make(map[string]msgHandler),
sendq: make(chan *pubMsg, 128),
statsz: eventsHBInterval,
orphMax: 5 * eventsHBInterval,
chkOrph: 3 * eventsHBInterval,
}
s.sys.client.initClient()
s.sys.client.echo = false
s.sys.wg.Add(1)
s.mu.Unlock()
// Register with the account.
s.sys.client.registerWithAccount(acc)
// Start our internal loop to serialize outbound messages.
// We do our own wg here since we will stop first during shutdown.
go s.internalSendLoop(&s.sys.wg)
// Start up our general subscriptions
s.initEventTracking()
// Track for dead remote servers.
s.wrapChk(s.startRemoteServerSweepTimer)()
// Send out statsz updates periodically.
s.wrapChk(s.startStatszTimer)()
return nil
} | go | func (s *Server) setSystemAccount(acc *Account) error {
if acc == nil {
return ErrMissingAccount
}
// Don't try to fix this here.
if acc.IsExpired() {
return ErrAccountExpired
}
// If we are running with trusted keys for an operator
// make sure we check the account is legit.
if !s.isTrustedIssuer(acc.Issuer) {
return ErrAccountValidation
}
s.mu.Lock()
if s.sys != nil {
s.mu.Unlock()
return ErrAccountExists
}
s.sys = &internal{
account: acc,
client: &client{srv: s, kind: SYSTEM, opts: internalOpts, msubs: -1, mpay: -1, start: time.Now(), last: time.Now()},
seq: 1,
sid: 1,
servers: make(map[string]*serverUpdate),
subs: make(map[string]msgHandler),
sendq: make(chan *pubMsg, 128),
statsz: eventsHBInterval,
orphMax: 5 * eventsHBInterval,
chkOrph: 3 * eventsHBInterval,
}
s.sys.client.initClient()
s.sys.client.echo = false
s.sys.wg.Add(1)
s.mu.Unlock()
// Register with the account.
s.sys.client.registerWithAccount(acc)
// Start our internal loop to serialize outbound messages.
// We do our own wg here since we will stop first during shutdown.
go s.internalSendLoop(&s.sys.wg)
// Start up our general subscriptions
s.initEventTracking()
// Track for dead remote servers.
s.wrapChk(s.startRemoteServerSweepTimer)()
// Send out statsz updates periodically.
s.wrapChk(s.startStatszTimer)()
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"setSystemAccount",
"(",
"acc",
"*",
"Account",
")",
"error",
"{",
"if",
"acc",
"==",
"nil",
"{",
"return",
"ErrMissingAccount",
"\n",
"}",
"\n",
"// Don't try to fix this here.",
"if",
"acc",
".",
"IsExpired",
"(",
")",
"{",
"return",
"ErrAccountExpired",
"\n",
"}",
"\n",
"// If we are running with trusted keys for an operator",
"// make sure we check the account is legit.",
"if",
"!",
"s",
".",
"isTrustedIssuer",
"(",
"acc",
".",
"Issuer",
")",
"{",
"return",
"ErrAccountValidation",
"\n",
"}",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n\n",
"if",
"s",
".",
"sys",
"!=",
"nil",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ErrAccountExists",
"\n",
"}",
"\n\n",
"s",
".",
"sys",
"=",
"&",
"internal",
"{",
"account",
":",
"acc",
",",
"client",
":",
"&",
"client",
"{",
"srv",
":",
"s",
",",
"kind",
":",
"SYSTEM",
",",
"opts",
":",
"internalOpts",
",",
"msubs",
":",
"-",
"1",
",",
"mpay",
":",
"-",
"1",
",",
"start",
":",
"time",
".",
"Now",
"(",
")",
",",
"last",
":",
"time",
".",
"Now",
"(",
")",
"}",
",",
"seq",
":",
"1",
",",
"sid",
":",
"1",
",",
"servers",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"serverUpdate",
")",
",",
"subs",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"msgHandler",
")",
",",
"sendq",
":",
"make",
"(",
"chan",
"*",
"pubMsg",
",",
"128",
")",
",",
"statsz",
":",
"eventsHBInterval",
",",
"orphMax",
":",
"5",
"*",
"eventsHBInterval",
",",
"chkOrph",
":",
"3",
"*",
"eventsHBInterval",
",",
"}",
"\n",
"s",
".",
"sys",
".",
"client",
".",
"initClient",
"(",
")",
"\n",
"s",
".",
"sys",
".",
"client",
".",
"echo",
"=",
"false",
"\n",
"s",
".",
"sys",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Register with the account.",
"s",
".",
"sys",
".",
"client",
".",
"registerWithAccount",
"(",
"acc",
")",
"\n\n",
"// Start our internal loop to serialize outbound messages.",
"// We do our own wg here since we will stop first during shutdown.",
"go",
"s",
".",
"internalSendLoop",
"(",
"&",
"s",
".",
"sys",
".",
"wg",
")",
"\n\n",
"// Start up our general subscriptions",
"s",
".",
"initEventTracking",
"(",
")",
"\n\n",
"// Track for dead remote servers.",
"s",
".",
"wrapChk",
"(",
"s",
".",
"startRemoteServerSweepTimer",
")",
"(",
")",
"\n\n",
"// Send out statsz updates periodically.",
"s",
".",
"wrapChk",
"(",
"s",
".",
"startStatszTimer",
")",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Assign a system account. Should only be called once.
// This sets up a server to send and receive messages from inside
// the server itself. | [
"Assign",
"a",
"system",
"account",
".",
"Should",
"only",
"be",
"called",
"once",
".",
"This",
"sets",
"up",
"a",
"server",
"to",
"send",
"and",
"receive",
"messages",
"from",
"inside",
"the",
"server",
"itself",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L649-L704 |
164,077 | nats-io/gnatsd | server/server.go | shouldTrackSubscriptions | func (s *Server) shouldTrackSubscriptions() bool {
return (s.opts.Cluster.Port != 0 || s.opts.Gateway.Port != 0)
} | go | func (s *Server) shouldTrackSubscriptions() bool {
return (s.opts.Cluster.Port != 0 || s.opts.Gateway.Port != 0)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"shouldTrackSubscriptions",
"(",
")",
"bool",
"{",
"return",
"(",
"s",
".",
"opts",
".",
"Cluster",
".",
"Port",
"!=",
"0",
"||",
"s",
".",
"opts",
".",
"Gateway",
".",
"Port",
"!=",
"0",
")",
"\n",
"}"
] | // Determine if accounts should track subscriptions for
// efficient propagation.
// Lock should be held on entry. | [
"Determine",
"if",
"accounts",
"should",
"track",
"subscriptions",
"for",
"efficient",
"propagation",
".",
"Lock",
"should",
"be",
"held",
"on",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L719-L721 |
164,078 | nats-io/gnatsd | server/server.go | registerAccount | func (s *Server) registerAccount(acc *Account) {
if acc.sl == nil {
acc.sl = NewSublist()
}
if acc.maxnae == 0 {
acc.maxnae = DEFAULT_MAX_ACCOUNT_AE_RESPONSE_MAPS
}
if acc.maxaettl == 0 {
acc.maxaettl = DEFAULT_TTL_AE_RESPONSE_MAP
}
if acc.clients == nil {
acc.clients = make(map[*client]*client)
}
// If we are capable of routing we will track subscription
// information for efficient interest propagation.
// During config reload, it is possible that account was
// already created (global account), so use locking and
// make sure we create only if needed.
acc.mu.Lock()
// TODO(dlc)- Double check that we need this for GWs.
if acc.rm == nil && s.opts != nil && s.shouldTrackSubscriptions() {
acc.rm = make(map[string]int32)
}
acc.srv = s
acc.mu.Unlock()
s.accounts.Store(acc.Name, acc)
s.enableAccountTracking(acc)
} | go | func (s *Server) registerAccount(acc *Account) {
if acc.sl == nil {
acc.sl = NewSublist()
}
if acc.maxnae == 0 {
acc.maxnae = DEFAULT_MAX_ACCOUNT_AE_RESPONSE_MAPS
}
if acc.maxaettl == 0 {
acc.maxaettl = DEFAULT_TTL_AE_RESPONSE_MAP
}
if acc.clients == nil {
acc.clients = make(map[*client]*client)
}
// If we are capable of routing we will track subscription
// information for efficient interest propagation.
// During config reload, it is possible that account was
// already created (global account), so use locking and
// make sure we create only if needed.
acc.mu.Lock()
// TODO(dlc)- Double check that we need this for GWs.
if acc.rm == nil && s.opts != nil && s.shouldTrackSubscriptions() {
acc.rm = make(map[string]int32)
}
acc.srv = s
acc.mu.Unlock()
s.accounts.Store(acc.Name, acc)
s.enableAccountTracking(acc)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"registerAccount",
"(",
"acc",
"*",
"Account",
")",
"{",
"if",
"acc",
".",
"sl",
"==",
"nil",
"{",
"acc",
".",
"sl",
"=",
"NewSublist",
"(",
")",
"\n",
"}",
"\n",
"if",
"acc",
".",
"maxnae",
"==",
"0",
"{",
"acc",
".",
"maxnae",
"=",
"DEFAULT_MAX_ACCOUNT_AE_RESPONSE_MAPS",
"\n",
"}",
"\n",
"if",
"acc",
".",
"maxaettl",
"==",
"0",
"{",
"acc",
".",
"maxaettl",
"=",
"DEFAULT_TTL_AE_RESPONSE_MAP",
"\n",
"}",
"\n",
"if",
"acc",
".",
"clients",
"==",
"nil",
"{",
"acc",
".",
"clients",
"=",
"make",
"(",
"map",
"[",
"*",
"client",
"]",
"*",
"client",
")",
"\n",
"}",
"\n",
"// If we are capable of routing we will track subscription",
"// information for efficient interest propagation.",
"// During config reload, it is possible that account was",
"// already created (global account), so use locking and",
"// make sure we create only if needed.",
"acc",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"// TODO(dlc)- Double check that we need this for GWs.",
"if",
"acc",
".",
"rm",
"==",
"nil",
"&&",
"s",
".",
"opts",
"!=",
"nil",
"&&",
"s",
".",
"shouldTrackSubscriptions",
"(",
")",
"{",
"acc",
".",
"rm",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"int32",
")",
"\n",
"}",
"\n",
"acc",
".",
"srv",
"=",
"s",
"\n",
"acc",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"accounts",
".",
"Store",
"(",
"acc",
".",
"Name",
",",
"acc",
")",
"\n",
"s",
".",
"enableAccountTracking",
"(",
"acc",
")",
"\n",
"}"
] | // Place common account setup here.
// Lock should be held on entry. | [
"Place",
"common",
"account",
"setup",
"here",
".",
"Lock",
"should",
"be",
"held",
"on",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L725-L752 |
164,079 | nats-io/gnatsd | server/server.go | lookupAccount | func (s *Server) lookupAccount(name string) (*Account, error) {
if v, ok := s.accounts.Load(name); ok {
acc := v.(*Account)
// If we are expired and we have a resolver, then
// return the latest information from the resolver.
if acc.IsExpired() {
var err error
s.mu.Lock()
if s.accResolver != nil {
err = s.updateAccount(acc)
}
s.mu.Unlock()
if err != nil {
return nil, err
}
}
return acc, nil
}
// If we have a resolver see if it can fetch the account.
if s.accResolver == nil {
return nil, ErrMissingAccount
}
s.mu.Lock()
acc, err := s.fetchAccount(name)
s.mu.Unlock()
return acc, err
} | go | func (s *Server) lookupAccount(name string) (*Account, error) {
if v, ok := s.accounts.Load(name); ok {
acc := v.(*Account)
// If we are expired and we have a resolver, then
// return the latest information from the resolver.
if acc.IsExpired() {
var err error
s.mu.Lock()
if s.accResolver != nil {
err = s.updateAccount(acc)
}
s.mu.Unlock()
if err != nil {
return nil, err
}
}
return acc, nil
}
// If we have a resolver see if it can fetch the account.
if s.accResolver == nil {
return nil, ErrMissingAccount
}
s.mu.Lock()
acc, err := s.fetchAccount(name)
s.mu.Unlock()
return acc, err
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"lookupAccount",
"(",
"name",
"string",
")",
"(",
"*",
"Account",
",",
"error",
")",
"{",
"if",
"v",
",",
"ok",
":=",
"s",
".",
"accounts",
".",
"Load",
"(",
"name",
")",
";",
"ok",
"{",
"acc",
":=",
"v",
".",
"(",
"*",
"Account",
")",
"\n",
"// If we are expired and we have a resolver, then",
"// return the latest information from the resolver.",
"if",
"acc",
".",
"IsExpired",
"(",
")",
"{",
"var",
"err",
"error",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"s",
".",
"accResolver",
"!=",
"nil",
"{",
"err",
"=",
"s",
".",
"updateAccount",
"(",
"acc",
")",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"acc",
",",
"nil",
"\n",
"}",
"\n",
"// If we have a resolver see if it can fetch the account.",
"if",
"s",
".",
"accResolver",
"==",
"nil",
"{",
"return",
"nil",
",",
"ErrMissingAccount",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"acc",
",",
"err",
":=",
"s",
".",
"fetchAccount",
"(",
"name",
")",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"acc",
",",
"err",
"\n",
"}"
] | // lookupAccount is a function to return the account structure
// associated with an account name. | [
"lookupAccount",
"is",
"a",
"function",
"to",
"return",
"the",
"account",
"structure",
"associated",
"with",
"an",
"account",
"name",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L756-L782 |
164,080 | nats-io/gnatsd | server/server.go | LookupAccount | func (s *Server) LookupAccount(name string) (*Account, error) {
return s.lookupAccount(name)
} | go | func (s *Server) LookupAccount(name string) (*Account, error) {
return s.lookupAccount(name)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"LookupAccount",
"(",
"name",
"string",
")",
"(",
"*",
"Account",
",",
"error",
")",
"{",
"return",
"s",
".",
"lookupAccount",
"(",
"name",
")",
"\n",
"}"
] | // LookupAccount is a public function to return the account structure
// associated with name. | [
"LookupAccount",
"is",
"a",
"public",
"function",
"to",
"return",
"the",
"account",
"structure",
"associated",
"with",
"name",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L786-L788 |
164,081 | nats-io/gnatsd | server/server.go | updateAccount | func (s *Server) updateAccount(acc *Account) error {
// TODO(dlc) - Make configurable
if time.Since(acc.updated) < time.Second {
s.Debugf("Requested account update for [%s] ignored, too soon", acc.Name)
return ErrAccountResolverUpdateTooSoon
}
claimJWT, err := s.fetchRawAccountClaims(acc.Name)
if err != nil {
return err
}
return s.updateAccountWithClaimJWT(acc, claimJWT)
} | go | func (s *Server) updateAccount(acc *Account) error {
// TODO(dlc) - Make configurable
if time.Since(acc.updated) < time.Second {
s.Debugf("Requested account update for [%s] ignored, too soon", acc.Name)
return ErrAccountResolverUpdateTooSoon
}
claimJWT, err := s.fetchRawAccountClaims(acc.Name)
if err != nil {
return err
}
return s.updateAccountWithClaimJWT(acc, claimJWT)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"updateAccount",
"(",
"acc",
"*",
"Account",
")",
"error",
"{",
"// TODO(dlc) - Make configurable",
"if",
"time",
".",
"Since",
"(",
"acc",
".",
"updated",
")",
"<",
"time",
".",
"Second",
"{",
"s",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"acc",
".",
"Name",
")",
"\n",
"return",
"ErrAccountResolverUpdateTooSoon",
"\n",
"}",
"\n",
"claimJWT",
",",
"err",
":=",
"s",
".",
"fetchRawAccountClaims",
"(",
"acc",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"s",
".",
"updateAccountWithClaimJWT",
"(",
"acc",
",",
"claimJWT",
")",
"\n",
"}"
] | // This will fetch new claims and if found update the account with new claims.
// Lock should be held upon entry. | [
"This",
"will",
"fetch",
"new",
"claims",
"and",
"if",
"found",
"update",
"the",
"account",
"with",
"new",
"claims",
".",
"Lock",
"should",
"be",
"held",
"upon",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L792-L803 |
164,082 | nats-io/gnatsd | server/server.go | updateAccountWithClaimJWT | func (s *Server) updateAccountWithClaimJWT(acc *Account, claimJWT string) error {
if acc == nil {
return ErrMissingAccount
}
acc.updated = time.Now()
if acc.claimJWT != "" && acc.claimJWT == claimJWT {
s.Debugf("Requested account update for [%s], same claims detected", acc.Name)
return ErrAccountResolverSameClaims
}
accClaims, _, err := s.verifyAccountClaims(claimJWT)
if err == nil && accClaims != nil {
acc.claimJWT = claimJWT
s.updateAccountClaims(acc, accClaims)
return nil
}
return err
} | go | func (s *Server) updateAccountWithClaimJWT(acc *Account, claimJWT string) error {
if acc == nil {
return ErrMissingAccount
}
acc.updated = time.Now()
if acc.claimJWT != "" && acc.claimJWT == claimJWT {
s.Debugf("Requested account update for [%s], same claims detected", acc.Name)
return ErrAccountResolverSameClaims
}
accClaims, _, err := s.verifyAccountClaims(claimJWT)
if err == nil && accClaims != nil {
acc.claimJWT = claimJWT
s.updateAccountClaims(acc, accClaims)
return nil
}
return err
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"updateAccountWithClaimJWT",
"(",
"acc",
"*",
"Account",
",",
"claimJWT",
"string",
")",
"error",
"{",
"if",
"acc",
"==",
"nil",
"{",
"return",
"ErrMissingAccount",
"\n",
"}",
"\n",
"acc",
".",
"updated",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"if",
"acc",
".",
"claimJWT",
"!=",
"\"",
"\"",
"&&",
"acc",
".",
"claimJWT",
"==",
"claimJWT",
"{",
"s",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"acc",
".",
"Name",
")",
"\n",
"return",
"ErrAccountResolverSameClaims",
"\n",
"}",
"\n",
"accClaims",
",",
"_",
",",
"err",
":=",
"s",
".",
"verifyAccountClaims",
"(",
"claimJWT",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"accClaims",
"!=",
"nil",
"{",
"acc",
".",
"claimJWT",
"=",
"claimJWT",
"\n",
"s",
".",
"updateAccountClaims",
"(",
"acc",
",",
"accClaims",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // updateAccountWithClaimJWT will check and apply the claim update. | [
"updateAccountWithClaimJWT",
"will",
"check",
"and",
"apply",
"the",
"claim",
"update",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L806-L822 |
164,083 | nats-io/gnatsd | server/server.go | fetchRawAccountClaims | func (s *Server) fetchRawAccountClaims(name string) (string, error) {
accResolver := s.accResolver
if accResolver == nil {
return "", ErrNoAccountResolver
}
// Need to do actual Fetch without the lock.
s.mu.Unlock()
start := time.Now()
claimJWT, err := accResolver.Fetch(name)
fetchTime := time.Since(start)
s.mu.Lock()
if fetchTime > time.Second {
s.Warnf("Account Fetch: %s in %v\n", name, fetchTime)
} else {
s.Debugf("Account Fetch: %s in %v\n", name, fetchTime)
}
if err != nil {
s.Warnf("Account Fetch Failed: %v\n", err)
return "", err
}
return claimJWT, nil
} | go | func (s *Server) fetchRawAccountClaims(name string) (string, error) {
accResolver := s.accResolver
if accResolver == nil {
return "", ErrNoAccountResolver
}
// Need to do actual Fetch without the lock.
s.mu.Unlock()
start := time.Now()
claimJWT, err := accResolver.Fetch(name)
fetchTime := time.Since(start)
s.mu.Lock()
if fetchTime > time.Second {
s.Warnf("Account Fetch: %s in %v\n", name, fetchTime)
} else {
s.Debugf("Account Fetch: %s in %v\n", name, fetchTime)
}
if err != nil {
s.Warnf("Account Fetch Failed: %v\n", err)
return "", err
}
return claimJWT, nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"fetchRawAccountClaims",
"(",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"accResolver",
":=",
"s",
".",
"accResolver",
"\n",
"if",
"accResolver",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"ErrNoAccountResolver",
"\n",
"}",
"\n",
"// Need to do actual Fetch without the lock.",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"claimJWT",
",",
"err",
":=",
"accResolver",
".",
"Fetch",
"(",
"name",
")",
"\n",
"fetchTime",
":=",
"time",
".",
"Since",
"(",
"start",
")",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"fetchTime",
">",
"time",
".",
"Second",
"{",
"s",
".",
"Warnf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
",",
"fetchTime",
")",
"\n",
"}",
"else",
"{",
"s",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
",",
"fetchTime",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"Warnf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"claimJWT",
",",
"nil",
"\n",
"}"
] | // fetchRawAccountClaims will grab raw account claims iff we have a resolver.
// Lock is held upon entry. | [
"fetchRawAccountClaims",
"will",
"grab",
"raw",
"account",
"claims",
"iff",
"we",
"have",
"a",
"resolver",
".",
"Lock",
"is",
"held",
"upon",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L826-L847 |
164,084 | nats-io/gnatsd | server/server.go | fetchAccountClaims | func (s *Server) fetchAccountClaims(name string) (*jwt.AccountClaims, string, error) {
claimJWT, err := s.fetchRawAccountClaims(name)
if err != nil {
return nil, _EMPTY_, err
}
return s.verifyAccountClaims(claimJWT)
} | go | func (s *Server) fetchAccountClaims(name string) (*jwt.AccountClaims, string, error) {
claimJWT, err := s.fetchRawAccountClaims(name)
if err != nil {
return nil, _EMPTY_, err
}
return s.verifyAccountClaims(claimJWT)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"fetchAccountClaims",
"(",
"name",
"string",
")",
"(",
"*",
"jwt",
".",
"AccountClaims",
",",
"string",
",",
"error",
")",
"{",
"claimJWT",
",",
"err",
":=",
"s",
".",
"fetchRawAccountClaims",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"_EMPTY_",
",",
"err",
"\n",
"}",
"\n",
"return",
"s",
".",
"verifyAccountClaims",
"(",
"claimJWT",
")",
"\n",
"}"
] | // fetchAccountClaims will attempt to fetch new claims if a resolver is present.
// Lock is held upon entry. | [
"fetchAccountClaims",
"will",
"attempt",
"to",
"fetch",
"new",
"claims",
"if",
"a",
"resolver",
"is",
"present",
".",
"Lock",
"is",
"held",
"upon",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L851-L857 |
164,085 | nats-io/gnatsd | server/server.go | verifyAccountClaims | func (s *Server) verifyAccountClaims(claimJWT string) (*jwt.AccountClaims, string, error) {
if accClaims, err := jwt.DecodeAccountClaims(claimJWT); err != nil {
return nil, _EMPTY_, err
} else {
vr := jwt.CreateValidationResults()
accClaims.Validate(vr)
if vr.IsBlocking(true) {
return nil, _EMPTY_, ErrAccountValidation
}
return accClaims, claimJWT, nil
}
} | go | func (s *Server) verifyAccountClaims(claimJWT string) (*jwt.AccountClaims, string, error) {
if accClaims, err := jwt.DecodeAccountClaims(claimJWT); err != nil {
return nil, _EMPTY_, err
} else {
vr := jwt.CreateValidationResults()
accClaims.Validate(vr)
if vr.IsBlocking(true) {
return nil, _EMPTY_, ErrAccountValidation
}
return accClaims, claimJWT, nil
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"verifyAccountClaims",
"(",
"claimJWT",
"string",
")",
"(",
"*",
"jwt",
".",
"AccountClaims",
",",
"string",
",",
"error",
")",
"{",
"if",
"accClaims",
",",
"err",
":=",
"jwt",
".",
"DecodeAccountClaims",
"(",
"claimJWT",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"_EMPTY_",
",",
"err",
"\n",
"}",
"else",
"{",
"vr",
":=",
"jwt",
".",
"CreateValidationResults",
"(",
")",
"\n",
"accClaims",
".",
"Validate",
"(",
"vr",
")",
"\n",
"if",
"vr",
".",
"IsBlocking",
"(",
"true",
")",
"{",
"return",
"nil",
",",
"_EMPTY_",
",",
"ErrAccountValidation",
"\n",
"}",
"\n",
"return",
"accClaims",
",",
"claimJWT",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // verifyAccountClaims will decode and validate any account claims. | [
"verifyAccountClaims",
"will",
"decode",
"and",
"validate",
"any",
"account",
"claims",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L860-L871 |
164,086 | nats-io/gnatsd | server/server.go | fetchAccount | func (s *Server) fetchAccount(name string) (*Account, error) {
if accClaims, claimJWT, err := s.fetchAccountClaims(name); accClaims != nil {
// We have released the lock during the low level fetch.
// Now that we are back under lock, check again if account
// is in the map or not. If it is, simply return it.
if v, ok := s.accounts.Load(name); ok {
acc := v.(*Account)
// Update with the new claims in case they are new.
// Following call will return ErrAccountResolverSameClaims
// if claims are the same.
err = s.updateAccountWithClaimJWT(acc, claimJWT)
if err != nil && err != ErrAccountResolverSameClaims {
return nil, err
}
return acc, nil
}
acc := s.buildInternalAccount(accClaims)
acc.claimJWT = claimJWT
s.registerAccount(acc)
return acc, nil
} else {
return nil, err
}
} | go | func (s *Server) fetchAccount(name string) (*Account, error) {
if accClaims, claimJWT, err := s.fetchAccountClaims(name); accClaims != nil {
// We have released the lock during the low level fetch.
// Now that we are back under lock, check again if account
// is in the map or not. If it is, simply return it.
if v, ok := s.accounts.Load(name); ok {
acc := v.(*Account)
// Update with the new claims in case they are new.
// Following call will return ErrAccountResolverSameClaims
// if claims are the same.
err = s.updateAccountWithClaimJWT(acc, claimJWT)
if err != nil && err != ErrAccountResolverSameClaims {
return nil, err
}
return acc, nil
}
acc := s.buildInternalAccount(accClaims)
acc.claimJWT = claimJWT
s.registerAccount(acc)
return acc, nil
} else {
return nil, err
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"fetchAccount",
"(",
"name",
"string",
")",
"(",
"*",
"Account",
",",
"error",
")",
"{",
"if",
"accClaims",
",",
"claimJWT",
",",
"err",
":=",
"s",
".",
"fetchAccountClaims",
"(",
"name",
")",
";",
"accClaims",
"!=",
"nil",
"{",
"// We have released the lock during the low level fetch.",
"// Now that we are back under lock, check again if account",
"// is in the map or not. If it is, simply return it.",
"if",
"v",
",",
"ok",
":=",
"s",
".",
"accounts",
".",
"Load",
"(",
"name",
")",
";",
"ok",
"{",
"acc",
":=",
"v",
".",
"(",
"*",
"Account",
")",
"\n",
"// Update with the new claims in case they are new.",
"// Following call will return ErrAccountResolverSameClaims",
"// if claims are the same.",
"err",
"=",
"s",
".",
"updateAccountWithClaimJWT",
"(",
"acc",
",",
"claimJWT",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"ErrAccountResolverSameClaims",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"acc",
",",
"nil",
"\n",
"}",
"\n",
"acc",
":=",
"s",
".",
"buildInternalAccount",
"(",
"accClaims",
")",
"\n",
"acc",
".",
"claimJWT",
"=",
"claimJWT",
"\n",
"s",
".",
"registerAccount",
"(",
"acc",
")",
"\n",
"return",
"acc",
",",
"nil",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // This will fetch an account from a resolver if defined.
// Lock should be held upon entry. | [
"This",
"will",
"fetch",
"an",
"account",
"from",
"a",
"resolver",
"if",
"defined",
".",
"Lock",
"should",
"be",
"held",
"upon",
"entry",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L875-L898 |
164,087 | nats-io/gnatsd | server/server.go | Start | func (s *Server) Start() {
s.Noticef("Starting nats-server version %s", VERSION)
s.Debugf("Go build version %s", s.info.GoVersion)
gc := gitCommit
if gc == "" {
gc = "not set"
}
s.Noticef("Git commit [%s]", gc)
// Check for insecure configurations.op
s.checkAuthforWarnings()
// Avoid RACE between Start() and Shutdown()
s.mu.Lock()
s.running = true
s.mu.Unlock()
s.grMu.Lock()
s.grRunning = true
s.grMu.Unlock()
// Snapshot server options.
opts := s.getOpts()
hasOperators := len(opts.TrustedOperators) > 0
if hasOperators {
s.Noticef("Trusted Operators")
}
for _, opc := range opts.TrustedOperators {
s.Noticef(" System : %q", opc.Audience)
s.Noticef(" Operator: %q", opc.Name)
s.Noticef(" Issued : %v", time.Unix(opc.IssuedAt, 0))
s.Noticef(" Expires : %v", time.Unix(opc.Expires, 0))
}
if hasOperators && opts.SystemAccount == _EMPTY_ {
s.Warnf("Trusted Operators should utilize a System Account")
}
// Log the pid to a file
if opts.PidFile != _EMPTY_ {
if err := s.logPid(); err != nil {
PrintAndDie(fmt.Sprintf("Could not write pidfile: %v\n", err))
}
}
// Start monitoring if needed
if err := s.StartMonitoring(); err != nil {
s.Fatalf("Can't start monitoring: %v", err)
return
}
// Setup system account which will start eventing stack.
if sa := opts.SystemAccount; sa != _EMPTY_ {
if err := s.SetSystemAccount(sa); err != nil {
s.Fatalf("Can't set system account: %v", err)
return
}
}
// Start up gateway if needed. Do this before starting the routes, because
// we want to resolve the gateway host:port so that this information can
// be sent to other routes.
if opts.Gateway.Port != 0 {
s.startGateways()
}
// Start up listen if we want to accept leaf node connections.
if opts.LeafNode.Port != 0 {
// Spin up the accept loop if needed
ch := make(chan struct{})
go s.leafNodeAcceptLoop(ch)
// This ensure that we have resolved or assigned the advertise
// address for the leafnode listener. We need that in StartRouting().
<-ch
}
// Solicit remote servers for leaf node connections.
if len(opts.LeafNode.Remotes) > 0 {
s.solicitLeafNodeRemotes(opts.LeafNode.Remotes)
}
// The Routing routine needs to wait for the client listen
// port to be opened and potential ephemeral port selected.
clientListenReady := make(chan struct{})
// Start up routing as well if needed.
if opts.Cluster.Port != 0 {
s.startGoRoutine(func() {
s.StartRouting(clientListenReady)
})
}
// Pprof http endpoint for the profiler.
if opts.ProfPort != 0 {
s.StartProfiler()
}
if opts.PortsFileDir != _EMPTY_ {
s.logPorts()
}
// Wait for clients.
s.AcceptLoop(clientListenReady)
} | go | func (s *Server) Start() {
s.Noticef("Starting nats-server version %s", VERSION)
s.Debugf("Go build version %s", s.info.GoVersion)
gc := gitCommit
if gc == "" {
gc = "not set"
}
s.Noticef("Git commit [%s]", gc)
// Check for insecure configurations.op
s.checkAuthforWarnings()
// Avoid RACE between Start() and Shutdown()
s.mu.Lock()
s.running = true
s.mu.Unlock()
s.grMu.Lock()
s.grRunning = true
s.grMu.Unlock()
// Snapshot server options.
opts := s.getOpts()
hasOperators := len(opts.TrustedOperators) > 0
if hasOperators {
s.Noticef("Trusted Operators")
}
for _, opc := range opts.TrustedOperators {
s.Noticef(" System : %q", opc.Audience)
s.Noticef(" Operator: %q", opc.Name)
s.Noticef(" Issued : %v", time.Unix(opc.IssuedAt, 0))
s.Noticef(" Expires : %v", time.Unix(opc.Expires, 0))
}
if hasOperators && opts.SystemAccount == _EMPTY_ {
s.Warnf("Trusted Operators should utilize a System Account")
}
// Log the pid to a file
if opts.PidFile != _EMPTY_ {
if err := s.logPid(); err != nil {
PrintAndDie(fmt.Sprintf("Could not write pidfile: %v\n", err))
}
}
// Start monitoring if needed
if err := s.StartMonitoring(); err != nil {
s.Fatalf("Can't start monitoring: %v", err)
return
}
// Setup system account which will start eventing stack.
if sa := opts.SystemAccount; sa != _EMPTY_ {
if err := s.SetSystemAccount(sa); err != nil {
s.Fatalf("Can't set system account: %v", err)
return
}
}
// Start up gateway if needed. Do this before starting the routes, because
// we want to resolve the gateway host:port so that this information can
// be sent to other routes.
if opts.Gateway.Port != 0 {
s.startGateways()
}
// Start up listen if we want to accept leaf node connections.
if opts.LeafNode.Port != 0 {
// Spin up the accept loop if needed
ch := make(chan struct{})
go s.leafNodeAcceptLoop(ch)
// This ensure that we have resolved or assigned the advertise
// address for the leafnode listener. We need that in StartRouting().
<-ch
}
// Solicit remote servers for leaf node connections.
if len(opts.LeafNode.Remotes) > 0 {
s.solicitLeafNodeRemotes(opts.LeafNode.Remotes)
}
// The Routing routine needs to wait for the client listen
// port to be opened and potential ephemeral port selected.
clientListenReady := make(chan struct{})
// Start up routing as well if needed.
if opts.Cluster.Port != 0 {
s.startGoRoutine(func() {
s.StartRouting(clientListenReady)
})
}
// Pprof http endpoint for the profiler.
if opts.ProfPort != 0 {
s.StartProfiler()
}
if opts.PortsFileDir != _EMPTY_ {
s.logPorts()
}
// Wait for clients.
s.AcceptLoop(clientListenReady)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Start",
"(",
")",
"{",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"VERSION",
")",
"\n",
"s",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"s",
".",
"info",
".",
"GoVersion",
")",
"\n",
"gc",
":=",
"gitCommit",
"\n",
"if",
"gc",
"==",
"\"",
"\"",
"{",
"gc",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"gc",
")",
"\n\n",
"// Check for insecure configurations.op",
"s",
".",
"checkAuthforWarnings",
"(",
")",
"\n\n",
"// Avoid RACE between Start() and Shutdown()",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"running",
"=",
"true",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"s",
".",
"grMu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"grRunning",
"=",
"true",
"\n",
"s",
".",
"grMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Snapshot server options.",
"opts",
":=",
"s",
".",
"getOpts",
"(",
")",
"\n\n",
"hasOperators",
":=",
"len",
"(",
"opts",
".",
"TrustedOperators",
")",
">",
"0",
"\n",
"if",
"hasOperators",
"{",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"opc",
":=",
"range",
"opts",
".",
"TrustedOperators",
"{",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"opc",
".",
"Audience",
")",
"\n",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"opc",
".",
"Name",
")",
"\n",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"time",
".",
"Unix",
"(",
"opc",
".",
"IssuedAt",
",",
"0",
")",
")",
"\n",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"time",
".",
"Unix",
"(",
"opc",
".",
"Expires",
",",
"0",
")",
")",
"\n",
"}",
"\n",
"if",
"hasOperators",
"&&",
"opts",
".",
"SystemAccount",
"==",
"_EMPTY_",
"{",
"s",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Log the pid to a file",
"if",
"opts",
".",
"PidFile",
"!=",
"_EMPTY_",
"{",
"if",
"err",
":=",
"s",
".",
"logPid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"PrintAndDie",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Start monitoring if needed",
"if",
"err",
":=",
"s",
".",
"StartMonitoring",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Setup system account which will start eventing stack.",
"if",
"sa",
":=",
"opts",
".",
"SystemAccount",
";",
"sa",
"!=",
"_EMPTY_",
"{",
"if",
"err",
":=",
"s",
".",
"SetSystemAccount",
"(",
"sa",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Start up gateway if needed. Do this before starting the routes, because",
"// we want to resolve the gateway host:port so that this information can",
"// be sent to other routes.",
"if",
"opts",
".",
"Gateway",
".",
"Port",
"!=",
"0",
"{",
"s",
".",
"startGateways",
"(",
")",
"\n",
"}",
"\n\n",
"// Start up listen if we want to accept leaf node connections.",
"if",
"opts",
".",
"LeafNode",
".",
"Port",
"!=",
"0",
"{",
"// Spin up the accept loop if needed",
"ch",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"s",
".",
"leafNodeAcceptLoop",
"(",
"ch",
")",
"\n",
"// This ensure that we have resolved or assigned the advertise",
"// address for the leafnode listener. We need that in StartRouting().",
"<-",
"ch",
"\n",
"}",
"\n\n",
"// Solicit remote servers for leaf node connections.",
"if",
"len",
"(",
"opts",
".",
"LeafNode",
".",
"Remotes",
")",
">",
"0",
"{",
"s",
".",
"solicitLeafNodeRemotes",
"(",
"opts",
".",
"LeafNode",
".",
"Remotes",
")",
"\n",
"}",
"\n\n",
"// The Routing routine needs to wait for the client listen",
"// port to be opened and potential ephemeral port selected.",
"clientListenReady",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n\n",
"// Start up routing as well if needed.",
"if",
"opts",
".",
"Cluster",
".",
"Port",
"!=",
"0",
"{",
"s",
".",
"startGoRoutine",
"(",
"func",
"(",
")",
"{",
"s",
".",
"StartRouting",
"(",
"clientListenReady",
")",
"\n",
"}",
")",
"\n",
"}",
"\n\n",
"// Pprof http endpoint for the profiler.",
"if",
"opts",
".",
"ProfPort",
"!=",
"0",
"{",
"s",
".",
"StartProfiler",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"opts",
".",
"PortsFileDir",
"!=",
"_EMPTY_",
"{",
"s",
".",
"logPorts",
"(",
")",
"\n",
"}",
"\n\n",
"// Wait for clients.",
"s",
".",
"AcceptLoop",
"(",
"clientListenReady",
")",
"\n",
"}"
] | // Start up the server, this will block.
// Start via a Go routine if needed. | [
"Start",
"up",
"the",
"server",
"this",
"will",
"block",
".",
"Start",
"via",
"a",
"Go",
"routine",
"if",
"needed",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L902-L1005 |
164,088 | nats-io/gnatsd | server/server.go | Shutdown | func (s *Server) Shutdown() {
// Shutdown the eventing system as needed.
// This is done first to send out any messages for
// account status. We will also clean up any
// eventing items associated with accounts.
s.shutdownEventing()
s.mu.Lock()
// Prevent issues with multiple calls.
if s.shutdown {
s.mu.Unlock()
return
}
s.Noticef("Server Exiting..")
opts := s.getOpts()
s.shutdown = true
s.running = false
s.grMu.Lock()
s.grRunning = false
s.grMu.Unlock()
conns := make(map[uint64]*client)
// Copy off the clients
for i, c := range s.clients {
conns[i] = c
}
// Copy off the connections that are not yet registered
// in s.routes, but for which the readLoop has started
s.grMu.Lock()
for i, c := range s.grTmpClients {
conns[i] = c
}
s.grMu.Unlock()
// Copy off the routes
for i, r := range s.routes {
conns[i] = r
}
// Copy off the gateways
s.getAllGatewayConnections(conns)
// Copy off the leaf nodes
for i, c := range s.leafs {
conns[i] = c
}
// Number of done channel responses we expect.
doneExpected := 0
// Kick client AcceptLoop()
if s.listener != nil {
doneExpected++
s.listener.Close()
s.listener = nil
}
// Kick leafnodes AcceptLoop()
if s.leafNodeListener != nil {
doneExpected++
s.leafNodeListener.Close()
s.leafNodeListener = nil
}
// Kick route AcceptLoop()
if s.routeListener != nil {
doneExpected++
s.routeListener.Close()
s.routeListener = nil
}
// Kick Gateway AcceptLoop()
if s.gatewayListener != nil {
doneExpected++
s.gatewayListener.Close()
s.gatewayListener = nil
}
// Kick HTTP monitoring if its running
if s.http != nil {
doneExpected++
s.http.Close()
s.http = nil
}
// Kick Profiling if its running
if s.profiler != nil {
doneExpected++
s.profiler.Close()
}
s.mu.Unlock()
// Release go routines that wait on that channel
close(s.quitCh)
// Close client and route connections
for _, c := range conns {
c.setNoReconnect()
c.closeConnection(ServerShutdown)
}
// Block until the accept loops exit
for doneExpected > 0 {
<-s.done
doneExpected--
}
// Wait for go routines to be done.
s.grWG.Wait()
if opts.PortsFileDir != _EMPTY_ {
s.deletePortsFile(opts.PortsFileDir)
}
// Close logger if applicable. It allows tests on Windows
// to be able to do proper cleanup (delete log file).
s.logging.RLock()
log := s.logging.logger
s.logging.RUnlock()
if log != nil {
if l, ok := log.(*logger.Logger); ok {
l.Close()
}
}
} | go | func (s *Server) Shutdown() {
// Shutdown the eventing system as needed.
// This is done first to send out any messages for
// account status. We will also clean up any
// eventing items associated with accounts.
s.shutdownEventing()
s.mu.Lock()
// Prevent issues with multiple calls.
if s.shutdown {
s.mu.Unlock()
return
}
s.Noticef("Server Exiting..")
opts := s.getOpts()
s.shutdown = true
s.running = false
s.grMu.Lock()
s.grRunning = false
s.grMu.Unlock()
conns := make(map[uint64]*client)
// Copy off the clients
for i, c := range s.clients {
conns[i] = c
}
// Copy off the connections that are not yet registered
// in s.routes, but for which the readLoop has started
s.grMu.Lock()
for i, c := range s.grTmpClients {
conns[i] = c
}
s.grMu.Unlock()
// Copy off the routes
for i, r := range s.routes {
conns[i] = r
}
// Copy off the gateways
s.getAllGatewayConnections(conns)
// Copy off the leaf nodes
for i, c := range s.leafs {
conns[i] = c
}
// Number of done channel responses we expect.
doneExpected := 0
// Kick client AcceptLoop()
if s.listener != nil {
doneExpected++
s.listener.Close()
s.listener = nil
}
// Kick leafnodes AcceptLoop()
if s.leafNodeListener != nil {
doneExpected++
s.leafNodeListener.Close()
s.leafNodeListener = nil
}
// Kick route AcceptLoop()
if s.routeListener != nil {
doneExpected++
s.routeListener.Close()
s.routeListener = nil
}
// Kick Gateway AcceptLoop()
if s.gatewayListener != nil {
doneExpected++
s.gatewayListener.Close()
s.gatewayListener = nil
}
// Kick HTTP monitoring if its running
if s.http != nil {
doneExpected++
s.http.Close()
s.http = nil
}
// Kick Profiling if its running
if s.profiler != nil {
doneExpected++
s.profiler.Close()
}
s.mu.Unlock()
// Release go routines that wait on that channel
close(s.quitCh)
// Close client and route connections
for _, c := range conns {
c.setNoReconnect()
c.closeConnection(ServerShutdown)
}
// Block until the accept loops exit
for doneExpected > 0 {
<-s.done
doneExpected--
}
// Wait for go routines to be done.
s.grWG.Wait()
if opts.PortsFileDir != _EMPTY_ {
s.deletePortsFile(opts.PortsFileDir)
}
// Close logger if applicable. It allows tests on Windows
// to be able to do proper cleanup (delete log file).
s.logging.RLock()
log := s.logging.logger
s.logging.RUnlock()
if log != nil {
if l, ok := log.(*logger.Logger); ok {
l.Close()
}
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Shutdown",
"(",
")",
"{",
"// Shutdown the eventing system as needed.",
"// This is done first to send out any messages for",
"// account status. We will also clean up any",
"// eventing items associated with accounts.",
"s",
".",
"shutdownEventing",
"(",
")",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"// Prevent issues with multiple calls.",
"if",
"s",
".",
"shutdown",
"{",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
")",
"\n\n",
"opts",
":=",
"s",
".",
"getOpts",
"(",
")",
"\n\n",
"s",
".",
"shutdown",
"=",
"true",
"\n",
"s",
".",
"running",
"=",
"false",
"\n",
"s",
".",
"grMu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"grRunning",
"=",
"false",
"\n",
"s",
".",
"grMu",
".",
"Unlock",
"(",
")",
"\n\n",
"conns",
":=",
"make",
"(",
"map",
"[",
"uint64",
"]",
"*",
"client",
")",
"\n\n",
"// Copy off the clients",
"for",
"i",
",",
"c",
":=",
"range",
"s",
".",
"clients",
"{",
"conns",
"[",
"i",
"]",
"=",
"c",
"\n",
"}",
"\n",
"// Copy off the connections that are not yet registered",
"// in s.routes, but for which the readLoop has started",
"s",
".",
"grMu",
".",
"Lock",
"(",
")",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"s",
".",
"grTmpClients",
"{",
"conns",
"[",
"i",
"]",
"=",
"c",
"\n",
"}",
"\n",
"s",
".",
"grMu",
".",
"Unlock",
"(",
")",
"\n",
"// Copy off the routes",
"for",
"i",
",",
"r",
":=",
"range",
"s",
".",
"routes",
"{",
"conns",
"[",
"i",
"]",
"=",
"r",
"\n",
"}",
"\n",
"// Copy off the gateways",
"s",
".",
"getAllGatewayConnections",
"(",
"conns",
")",
"\n\n",
"// Copy off the leaf nodes",
"for",
"i",
",",
"c",
":=",
"range",
"s",
".",
"leafs",
"{",
"conns",
"[",
"i",
"]",
"=",
"c",
"\n",
"}",
"\n\n",
"// Number of done channel responses we expect.",
"doneExpected",
":=",
"0",
"\n\n",
"// Kick client AcceptLoop()",
"if",
"s",
".",
"listener",
"!=",
"nil",
"{",
"doneExpected",
"++",
"\n",
"s",
".",
"listener",
".",
"Close",
"(",
")",
"\n",
"s",
".",
"listener",
"=",
"nil",
"\n",
"}",
"\n\n",
"// Kick leafnodes AcceptLoop()",
"if",
"s",
".",
"leafNodeListener",
"!=",
"nil",
"{",
"doneExpected",
"++",
"\n",
"s",
".",
"leafNodeListener",
".",
"Close",
"(",
")",
"\n",
"s",
".",
"leafNodeListener",
"=",
"nil",
"\n",
"}",
"\n\n",
"// Kick route AcceptLoop()",
"if",
"s",
".",
"routeListener",
"!=",
"nil",
"{",
"doneExpected",
"++",
"\n",
"s",
".",
"routeListener",
".",
"Close",
"(",
")",
"\n",
"s",
".",
"routeListener",
"=",
"nil",
"\n",
"}",
"\n\n",
"// Kick Gateway AcceptLoop()",
"if",
"s",
".",
"gatewayListener",
"!=",
"nil",
"{",
"doneExpected",
"++",
"\n",
"s",
".",
"gatewayListener",
".",
"Close",
"(",
")",
"\n",
"s",
".",
"gatewayListener",
"=",
"nil",
"\n",
"}",
"\n\n",
"// Kick HTTP monitoring if its running",
"if",
"s",
".",
"http",
"!=",
"nil",
"{",
"doneExpected",
"++",
"\n",
"s",
".",
"http",
".",
"Close",
"(",
")",
"\n",
"s",
".",
"http",
"=",
"nil",
"\n",
"}",
"\n\n",
"// Kick Profiling if its running",
"if",
"s",
".",
"profiler",
"!=",
"nil",
"{",
"doneExpected",
"++",
"\n",
"s",
".",
"profiler",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Release go routines that wait on that channel",
"close",
"(",
"s",
".",
"quitCh",
")",
"\n\n",
"// Close client and route connections",
"for",
"_",
",",
"c",
":=",
"range",
"conns",
"{",
"c",
".",
"setNoReconnect",
"(",
")",
"\n",
"c",
".",
"closeConnection",
"(",
"ServerShutdown",
")",
"\n",
"}",
"\n\n",
"// Block until the accept loops exit",
"for",
"doneExpected",
">",
"0",
"{",
"<-",
"s",
".",
"done",
"\n",
"doneExpected",
"--",
"\n",
"}",
"\n\n",
"// Wait for go routines to be done.",
"s",
".",
"grWG",
".",
"Wait",
"(",
")",
"\n\n",
"if",
"opts",
".",
"PortsFileDir",
"!=",
"_EMPTY_",
"{",
"s",
".",
"deletePortsFile",
"(",
"opts",
".",
"PortsFileDir",
")",
"\n",
"}",
"\n\n",
"// Close logger if applicable. It allows tests on Windows",
"// to be able to do proper cleanup (delete log file).",
"s",
".",
"logging",
".",
"RLock",
"(",
")",
"\n",
"log",
":=",
"s",
".",
"logging",
".",
"logger",
"\n",
"s",
".",
"logging",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"log",
"!=",
"nil",
"{",
"if",
"l",
",",
"ok",
":=",
"log",
".",
"(",
"*",
"logger",
".",
"Logger",
")",
";",
"ok",
"{",
"l",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Shutdown will shutdown the server instance by kicking out the AcceptLoop
// and closing all associated clients. | [
"Shutdown",
"will",
"shutdown",
"the",
"server",
"instance",
"by",
"kicking",
"out",
"the",
"AcceptLoop",
"and",
"closing",
"all",
"associated",
"clients",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1009-L1135 |
164,089 | nats-io/gnatsd | server/server.go | AcceptLoop | func (s *Server) AcceptLoop(clr chan struct{}) {
// If we were to exit before the listener is setup properly,
// make sure we close the channel.
defer func() {
if clr != nil {
close(clr)
}
}()
// Snapshot server options.
opts := s.getOpts()
hp := net.JoinHostPort(opts.Host, strconv.Itoa(opts.Port))
l, e := net.Listen("tcp", hp)
if e != nil {
s.Fatalf("Error listening on port: %s, %q", hp, e)
return
}
s.Noticef("Listening for client connections on %s",
net.JoinHostPort(opts.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
// Alert of TLS enabled.
if opts.TLSConfig != nil {
s.Noticef("TLS required for client connections")
}
s.Noticef("Server id is %s", s.info.ID)
s.Noticef("Server is ready")
// Setup state that can enable shutdown
s.mu.Lock()
s.listener = l
// If server was started with RANDOM_PORT (-1), opts.Port would be equal
// to 0 at the beginning this function. So we need to get the actual port
if opts.Port == 0 {
// Write resolved port back to options.
opts.Port = l.Addr().(*net.TCPAddr).Port
}
// Now that port has been set (if it was set to RANDOM), set the
// server's info Host/Port with either values from Options or
// ClientAdvertise. Also generate the JSON byte array.
if err := s.setInfoHostPortAndGenerateJSON(); err != nil {
s.Fatalf("Error setting server INFO with ClientAdvertise value of %s, err=%v", s.opts.ClientAdvertise, err)
s.mu.Unlock()
return
}
// Keep track of client connect URLs. We may need them later.
s.clientConnectURLs = s.getClientConnectURLs()
s.mu.Unlock()
// Let the caller know that we are ready
close(clr)
clr = nil
tmpDelay := ACCEPT_MIN_SLEEP
for s.isRunning() {
conn, err := l.Accept()
if err != nil {
if s.isLameDuckMode() {
// Signal that we are not accepting new clients
s.ldmCh <- true
// Now wait for the Shutdown...
<-s.quitCh
return
}
tmpDelay = s.acceptError("Client", err, tmpDelay)
continue
}
tmpDelay = ACCEPT_MIN_SLEEP
s.startGoRoutine(func() {
s.createClient(conn)
s.grWG.Done()
})
}
s.done <- true
} | go | func (s *Server) AcceptLoop(clr chan struct{}) {
// If we were to exit before the listener is setup properly,
// make sure we close the channel.
defer func() {
if clr != nil {
close(clr)
}
}()
// Snapshot server options.
opts := s.getOpts()
hp := net.JoinHostPort(opts.Host, strconv.Itoa(opts.Port))
l, e := net.Listen("tcp", hp)
if e != nil {
s.Fatalf("Error listening on port: %s, %q", hp, e)
return
}
s.Noticef("Listening for client connections on %s",
net.JoinHostPort(opts.Host, strconv.Itoa(l.Addr().(*net.TCPAddr).Port)))
// Alert of TLS enabled.
if opts.TLSConfig != nil {
s.Noticef("TLS required for client connections")
}
s.Noticef("Server id is %s", s.info.ID)
s.Noticef("Server is ready")
// Setup state that can enable shutdown
s.mu.Lock()
s.listener = l
// If server was started with RANDOM_PORT (-1), opts.Port would be equal
// to 0 at the beginning this function. So we need to get the actual port
if opts.Port == 0 {
// Write resolved port back to options.
opts.Port = l.Addr().(*net.TCPAddr).Port
}
// Now that port has been set (if it was set to RANDOM), set the
// server's info Host/Port with either values from Options or
// ClientAdvertise. Also generate the JSON byte array.
if err := s.setInfoHostPortAndGenerateJSON(); err != nil {
s.Fatalf("Error setting server INFO with ClientAdvertise value of %s, err=%v", s.opts.ClientAdvertise, err)
s.mu.Unlock()
return
}
// Keep track of client connect URLs. We may need them later.
s.clientConnectURLs = s.getClientConnectURLs()
s.mu.Unlock()
// Let the caller know that we are ready
close(clr)
clr = nil
tmpDelay := ACCEPT_MIN_SLEEP
for s.isRunning() {
conn, err := l.Accept()
if err != nil {
if s.isLameDuckMode() {
// Signal that we are not accepting new clients
s.ldmCh <- true
// Now wait for the Shutdown...
<-s.quitCh
return
}
tmpDelay = s.acceptError("Client", err, tmpDelay)
continue
}
tmpDelay = ACCEPT_MIN_SLEEP
s.startGoRoutine(func() {
s.createClient(conn)
s.grWG.Done()
})
}
s.done <- true
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"AcceptLoop",
"(",
"clr",
"chan",
"struct",
"{",
"}",
")",
"{",
"// If we were to exit before the listener is setup properly,",
"// make sure we close the channel.",
"defer",
"func",
"(",
")",
"{",
"if",
"clr",
"!=",
"nil",
"{",
"close",
"(",
"clr",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// Snapshot server options.",
"opts",
":=",
"s",
".",
"getOpts",
"(",
")",
"\n\n",
"hp",
":=",
"net",
".",
"JoinHostPort",
"(",
"opts",
".",
"Host",
",",
"strconv",
".",
"Itoa",
"(",
"opts",
".",
"Port",
")",
")",
"\n",
"l",
",",
"e",
":=",
"net",
".",
"Listen",
"(",
"\"",
"\"",
",",
"hp",
")",
"\n",
"if",
"e",
"!=",
"nil",
"{",
"s",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"hp",
",",
"e",
")",
"\n",
"return",
"\n",
"}",
"\n",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"net",
".",
"JoinHostPort",
"(",
"opts",
".",
"Host",
",",
"strconv",
".",
"Itoa",
"(",
"l",
".",
"Addr",
"(",
")",
".",
"(",
"*",
"net",
".",
"TCPAddr",
")",
".",
"Port",
")",
")",
")",
"\n\n",
"// Alert of TLS enabled.",
"if",
"opts",
".",
"TLSConfig",
"!=",
"nil",
"{",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"s",
".",
"info",
".",
"ID",
")",
"\n",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
")",
"\n\n",
"// Setup state that can enable shutdown",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"listener",
"=",
"l",
"\n\n",
"// If server was started with RANDOM_PORT (-1), opts.Port would be equal",
"// to 0 at the beginning this function. So we need to get the actual port",
"if",
"opts",
".",
"Port",
"==",
"0",
"{",
"// Write resolved port back to options.",
"opts",
".",
"Port",
"=",
"l",
".",
"Addr",
"(",
")",
".",
"(",
"*",
"net",
".",
"TCPAddr",
")",
".",
"Port",
"\n",
"}",
"\n\n",
"// Now that port has been set (if it was set to RANDOM), set the",
"// server's info Host/Port with either values from Options or",
"// ClientAdvertise. Also generate the JSON byte array.",
"if",
"err",
":=",
"s",
".",
"setInfoHostPortAndGenerateJSON",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"s",
".",
"opts",
".",
"ClientAdvertise",
",",
"err",
")",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Keep track of client connect URLs. We may need them later.",
"s",
".",
"clientConnectURLs",
"=",
"s",
".",
"getClientConnectURLs",
"(",
")",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Let the caller know that we are ready",
"close",
"(",
"clr",
")",
"\n",
"clr",
"=",
"nil",
"\n\n",
"tmpDelay",
":=",
"ACCEPT_MIN_SLEEP",
"\n\n",
"for",
"s",
".",
"isRunning",
"(",
")",
"{",
"conn",
",",
"err",
":=",
"l",
".",
"Accept",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"s",
".",
"isLameDuckMode",
"(",
")",
"{",
"// Signal that we are not accepting new clients",
"s",
".",
"ldmCh",
"<-",
"true",
"\n",
"// Now wait for the Shutdown...",
"<-",
"s",
".",
"quitCh",
"\n",
"return",
"\n",
"}",
"\n",
"tmpDelay",
"=",
"s",
".",
"acceptError",
"(",
"\"",
"\"",
",",
"err",
",",
"tmpDelay",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"tmpDelay",
"=",
"ACCEPT_MIN_SLEEP",
"\n",
"s",
".",
"startGoRoutine",
"(",
"func",
"(",
")",
"{",
"s",
".",
"createClient",
"(",
"conn",
")",
"\n",
"s",
".",
"grWG",
".",
"Done",
"(",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"s",
".",
"done",
"<-",
"true",
"\n",
"}"
] | // AcceptLoop is exported for easier testing. | [
"AcceptLoop",
"is",
"exported",
"for",
"easier",
"testing",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1138-L1216 |
164,090 | nats-io/gnatsd | server/server.go | StartProfiler | func (s *Server) StartProfiler() {
// Snapshot server options.
opts := s.getOpts()
port := opts.ProfPort
// Check for Random Port
if port == -1 {
port = 0
}
hp := net.JoinHostPort(opts.Host, strconv.Itoa(port))
l, err := net.Listen("tcp", hp)
s.Noticef("profiling port: %d", l.Addr().(*net.TCPAddr).Port)
if err != nil {
s.Fatalf("error starting profiler: %s", err)
}
srv := &http.Server{
Addr: hp,
Handler: http.DefaultServeMux,
MaxHeaderBytes: 1 << 20,
}
s.mu.Lock()
s.profiler = l
s.profilingServer = srv
s.mu.Unlock()
go func() {
// if this errors out, it's probably because the server is being shutdown
err := srv.Serve(l)
if err != nil {
s.mu.Lock()
shutdown := s.shutdown
s.mu.Unlock()
if !shutdown {
s.Fatalf("error starting profiler: %s", err)
}
}
s.done <- true
}()
} | go | func (s *Server) StartProfiler() {
// Snapshot server options.
opts := s.getOpts()
port := opts.ProfPort
// Check for Random Port
if port == -1 {
port = 0
}
hp := net.JoinHostPort(opts.Host, strconv.Itoa(port))
l, err := net.Listen("tcp", hp)
s.Noticef("profiling port: %d", l.Addr().(*net.TCPAddr).Port)
if err != nil {
s.Fatalf("error starting profiler: %s", err)
}
srv := &http.Server{
Addr: hp,
Handler: http.DefaultServeMux,
MaxHeaderBytes: 1 << 20,
}
s.mu.Lock()
s.profiler = l
s.profilingServer = srv
s.mu.Unlock()
go func() {
// if this errors out, it's probably because the server is being shutdown
err := srv.Serve(l)
if err != nil {
s.mu.Lock()
shutdown := s.shutdown
s.mu.Unlock()
if !shutdown {
s.Fatalf("error starting profiler: %s", err)
}
}
s.done <- true
}()
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"StartProfiler",
"(",
")",
"{",
"// Snapshot server options.",
"opts",
":=",
"s",
".",
"getOpts",
"(",
")",
"\n\n",
"port",
":=",
"opts",
".",
"ProfPort",
"\n\n",
"// Check for Random Port",
"if",
"port",
"==",
"-",
"1",
"{",
"port",
"=",
"0",
"\n",
"}",
"\n\n",
"hp",
":=",
"net",
".",
"JoinHostPort",
"(",
"opts",
".",
"Host",
",",
"strconv",
".",
"Itoa",
"(",
"port",
")",
")",
"\n\n",
"l",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"",
"\"",
",",
"hp",
")",
"\n",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"l",
".",
"Addr",
"(",
")",
".",
"(",
"*",
"net",
".",
"TCPAddr",
")",
".",
"Port",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"srv",
":=",
"&",
"http",
".",
"Server",
"{",
"Addr",
":",
"hp",
",",
"Handler",
":",
"http",
".",
"DefaultServeMux",
",",
"MaxHeaderBytes",
":",
"1",
"<<",
"20",
",",
"}",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"profiler",
"=",
"l",
"\n",
"s",
".",
"profilingServer",
"=",
"srv",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"// if this errors out, it's probably because the server is being shutdown",
"err",
":=",
"srv",
".",
"Serve",
"(",
"l",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"shutdown",
":=",
"s",
".",
"shutdown",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"shutdown",
"{",
"s",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"done",
"<-",
"true",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // StartProfiler is called to enable dynamic profiling. | [
"StartProfiler",
"is",
"called",
"to",
"enable",
"dynamic",
"profiling",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1242-L1286 |
164,091 | nats-io/gnatsd | server/server.go | StartMonitoring | func (s *Server) StartMonitoring() error {
// Snapshot server options.
opts := s.getOpts()
// Specifying both HTTP and HTTPS ports is a misconfiguration
if opts.HTTPPort != 0 && opts.HTTPSPort != 0 {
return fmt.Errorf("can't specify both HTTP (%v) and HTTPs (%v) ports", opts.HTTPPort, opts.HTTPSPort)
}
var err error
if opts.HTTPPort != 0 {
err = s.startMonitoring(false)
} else if opts.HTTPSPort != 0 {
if opts.TLSConfig == nil {
return fmt.Errorf("TLS cert and key required for HTTPS")
}
err = s.startMonitoring(true)
}
return err
} | go | func (s *Server) StartMonitoring() error {
// Snapshot server options.
opts := s.getOpts()
// Specifying both HTTP and HTTPS ports is a misconfiguration
if opts.HTTPPort != 0 && opts.HTTPSPort != 0 {
return fmt.Errorf("can't specify both HTTP (%v) and HTTPs (%v) ports", opts.HTTPPort, opts.HTTPSPort)
}
var err error
if opts.HTTPPort != 0 {
err = s.startMonitoring(false)
} else if opts.HTTPSPort != 0 {
if opts.TLSConfig == nil {
return fmt.Errorf("TLS cert and key required for HTTPS")
}
err = s.startMonitoring(true)
}
return err
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"StartMonitoring",
"(",
")",
"error",
"{",
"// Snapshot server options.",
"opts",
":=",
"s",
".",
"getOpts",
"(",
")",
"\n\n",
"// Specifying both HTTP and HTTPS ports is a misconfiguration",
"if",
"opts",
".",
"HTTPPort",
"!=",
"0",
"&&",
"opts",
".",
"HTTPSPort",
"!=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"opts",
".",
"HTTPPort",
",",
"opts",
".",
"HTTPSPort",
")",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"if",
"opts",
".",
"HTTPPort",
"!=",
"0",
"{",
"err",
"=",
"s",
".",
"startMonitoring",
"(",
"false",
")",
"\n",
"}",
"else",
"if",
"opts",
".",
"HTTPSPort",
"!=",
"0",
"{",
"if",
"opts",
".",
"TLSConfig",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"s",
".",
"startMonitoring",
"(",
"true",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // StartMonitoring starts the HTTP or HTTPs server if needed. | [
"StartMonitoring",
"starts",
"the",
"HTTP",
"or",
"HTTPs",
"server",
"if",
"needed",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1301-L1319 |
164,092 | nats-io/gnatsd | server/server.go | startMonitoring | func (s *Server) startMonitoring(secure bool) error {
// Snapshot server options.
opts := s.getOpts()
// Used to track HTTP requests
s.httpReqStats = map[string]uint64{
RootPath: 0,
VarzPath: 0,
ConnzPath: 0,
RoutezPath: 0,
SubszPath: 0,
}
var (
hp string
err error
httpListener net.Listener
port int
)
monitorProtocol := "http"
if secure {
monitorProtocol += "s"
port = opts.HTTPSPort
if port == -1 {
port = 0
}
hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
config := opts.TLSConfig.Clone()
config.ClientAuth = tls.NoClientCert
httpListener, err = tls.Listen("tcp", hp, config)
} else {
port = opts.HTTPPort
if port == -1 {
port = 0
}
hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
httpListener, err = net.Listen("tcp", hp)
}
if err != nil {
return fmt.Errorf("can't listen to the monitor port: %v", err)
}
s.Noticef("Starting %s monitor on %s", monitorProtocol,
net.JoinHostPort(opts.HTTPHost, strconv.Itoa(httpListener.Addr().(*net.TCPAddr).Port)))
mux := http.NewServeMux()
// Root
mux.HandleFunc(RootPath, s.HandleRoot)
// Varz
mux.HandleFunc(VarzPath, s.HandleVarz)
// Connz
mux.HandleFunc(ConnzPath, s.HandleConnz)
// Routez
mux.HandleFunc(RoutezPath, s.HandleRoutez)
// Subz
mux.HandleFunc(SubszPath, s.HandleSubsz)
// Subz alias for backwards compatibility
mux.HandleFunc("/subscriptionsz", s.HandleSubsz)
// Stacksz
mux.HandleFunc(StackszPath, s.HandleStacksz)
// Do not set a WriteTimeout because it could cause cURL/browser
// to return empty response or unable to display page if the
// server needs more time to build the response.
srv := &http.Server{
Addr: hp,
Handler: mux,
MaxHeaderBytes: 1 << 20,
}
s.mu.Lock()
s.http = httpListener
s.httpHandler = mux
s.monitoringServer = srv
s.mu.Unlock()
go func() {
srv.Serve(httpListener)
srv.Handler = nil
s.mu.Lock()
s.httpHandler = nil
s.mu.Unlock()
s.done <- true
}()
return nil
} | go | func (s *Server) startMonitoring(secure bool) error {
// Snapshot server options.
opts := s.getOpts()
// Used to track HTTP requests
s.httpReqStats = map[string]uint64{
RootPath: 0,
VarzPath: 0,
ConnzPath: 0,
RoutezPath: 0,
SubszPath: 0,
}
var (
hp string
err error
httpListener net.Listener
port int
)
monitorProtocol := "http"
if secure {
monitorProtocol += "s"
port = opts.HTTPSPort
if port == -1 {
port = 0
}
hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
config := opts.TLSConfig.Clone()
config.ClientAuth = tls.NoClientCert
httpListener, err = tls.Listen("tcp", hp, config)
} else {
port = opts.HTTPPort
if port == -1 {
port = 0
}
hp = net.JoinHostPort(opts.HTTPHost, strconv.Itoa(port))
httpListener, err = net.Listen("tcp", hp)
}
if err != nil {
return fmt.Errorf("can't listen to the monitor port: %v", err)
}
s.Noticef("Starting %s monitor on %s", monitorProtocol,
net.JoinHostPort(opts.HTTPHost, strconv.Itoa(httpListener.Addr().(*net.TCPAddr).Port)))
mux := http.NewServeMux()
// Root
mux.HandleFunc(RootPath, s.HandleRoot)
// Varz
mux.HandleFunc(VarzPath, s.HandleVarz)
// Connz
mux.HandleFunc(ConnzPath, s.HandleConnz)
// Routez
mux.HandleFunc(RoutezPath, s.HandleRoutez)
// Subz
mux.HandleFunc(SubszPath, s.HandleSubsz)
// Subz alias for backwards compatibility
mux.HandleFunc("/subscriptionsz", s.HandleSubsz)
// Stacksz
mux.HandleFunc(StackszPath, s.HandleStacksz)
// Do not set a WriteTimeout because it could cause cURL/browser
// to return empty response or unable to display page if the
// server needs more time to build the response.
srv := &http.Server{
Addr: hp,
Handler: mux,
MaxHeaderBytes: 1 << 20,
}
s.mu.Lock()
s.http = httpListener
s.httpHandler = mux
s.monitoringServer = srv
s.mu.Unlock()
go func() {
srv.Serve(httpListener)
srv.Handler = nil
s.mu.Lock()
s.httpHandler = nil
s.mu.Unlock()
s.done <- true
}()
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"startMonitoring",
"(",
"secure",
"bool",
")",
"error",
"{",
"// Snapshot server options.",
"opts",
":=",
"s",
".",
"getOpts",
"(",
")",
"\n\n",
"// Used to track HTTP requests",
"s",
".",
"httpReqStats",
"=",
"map",
"[",
"string",
"]",
"uint64",
"{",
"RootPath",
":",
"0",
",",
"VarzPath",
":",
"0",
",",
"ConnzPath",
":",
"0",
",",
"RoutezPath",
":",
"0",
",",
"SubszPath",
":",
"0",
",",
"}",
"\n\n",
"var",
"(",
"hp",
"string",
"\n",
"err",
"error",
"\n",
"httpListener",
"net",
".",
"Listener",
"\n",
"port",
"int",
"\n",
")",
"\n\n",
"monitorProtocol",
":=",
"\"",
"\"",
"\n\n",
"if",
"secure",
"{",
"monitorProtocol",
"+=",
"\"",
"\"",
"\n",
"port",
"=",
"opts",
".",
"HTTPSPort",
"\n",
"if",
"port",
"==",
"-",
"1",
"{",
"port",
"=",
"0",
"\n",
"}",
"\n",
"hp",
"=",
"net",
".",
"JoinHostPort",
"(",
"opts",
".",
"HTTPHost",
",",
"strconv",
".",
"Itoa",
"(",
"port",
")",
")",
"\n",
"config",
":=",
"opts",
".",
"TLSConfig",
".",
"Clone",
"(",
")",
"\n",
"config",
".",
"ClientAuth",
"=",
"tls",
".",
"NoClientCert",
"\n",
"httpListener",
",",
"err",
"=",
"tls",
".",
"Listen",
"(",
"\"",
"\"",
",",
"hp",
",",
"config",
")",
"\n\n",
"}",
"else",
"{",
"port",
"=",
"opts",
".",
"HTTPPort",
"\n",
"if",
"port",
"==",
"-",
"1",
"{",
"port",
"=",
"0",
"\n",
"}",
"\n",
"hp",
"=",
"net",
".",
"JoinHostPort",
"(",
"opts",
".",
"HTTPHost",
",",
"strconv",
".",
"Itoa",
"(",
"port",
")",
")",
"\n",
"httpListener",
",",
"err",
"=",
"net",
".",
"Listen",
"(",
"\"",
"\"",
",",
"hp",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"s",
".",
"Noticef",
"(",
"\"",
"\"",
",",
"monitorProtocol",
",",
"net",
".",
"JoinHostPort",
"(",
"opts",
".",
"HTTPHost",
",",
"strconv",
".",
"Itoa",
"(",
"httpListener",
".",
"Addr",
"(",
")",
".",
"(",
"*",
"net",
".",
"TCPAddr",
")",
".",
"Port",
")",
")",
")",
"\n\n",
"mux",
":=",
"http",
".",
"NewServeMux",
"(",
")",
"\n\n",
"// Root",
"mux",
".",
"HandleFunc",
"(",
"RootPath",
",",
"s",
".",
"HandleRoot",
")",
"\n",
"// Varz",
"mux",
".",
"HandleFunc",
"(",
"VarzPath",
",",
"s",
".",
"HandleVarz",
")",
"\n",
"// Connz",
"mux",
".",
"HandleFunc",
"(",
"ConnzPath",
",",
"s",
".",
"HandleConnz",
")",
"\n",
"// Routez",
"mux",
".",
"HandleFunc",
"(",
"RoutezPath",
",",
"s",
".",
"HandleRoutez",
")",
"\n",
"// Subz",
"mux",
".",
"HandleFunc",
"(",
"SubszPath",
",",
"s",
".",
"HandleSubsz",
")",
"\n",
"// Subz alias for backwards compatibility",
"mux",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"s",
".",
"HandleSubsz",
")",
"\n",
"// Stacksz",
"mux",
".",
"HandleFunc",
"(",
"StackszPath",
",",
"s",
".",
"HandleStacksz",
")",
"\n\n",
"// Do not set a WriteTimeout because it could cause cURL/browser",
"// to return empty response or unable to display page if the",
"// server needs more time to build the response.",
"srv",
":=",
"&",
"http",
".",
"Server",
"{",
"Addr",
":",
"hp",
",",
"Handler",
":",
"mux",
",",
"MaxHeaderBytes",
":",
"1",
"<<",
"20",
",",
"}",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"http",
"=",
"httpListener",
"\n",
"s",
".",
"httpHandler",
"=",
"mux",
"\n",
"s",
".",
"monitoringServer",
"=",
"srv",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"srv",
".",
"Serve",
"(",
"httpListener",
")",
"\n",
"srv",
".",
"Handler",
"=",
"nil",
"\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"httpHandler",
"=",
"nil",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"done",
"<-",
"true",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Start the monitoring server | [
"Start",
"the",
"monitoring",
"server"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1332-L1422 |
164,093 | nats-io/gnatsd | server/server.go | copyInfo | func (s *Server) copyInfo() Info {
info := s.info
if info.ClientConnectURLs != nil {
info.ClientConnectURLs = make([]string, len(s.info.ClientConnectURLs))
copy(info.ClientConnectURLs, s.info.ClientConnectURLs)
}
if s.nonceRequired() {
// Nonce handling
var raw [nonceLen]byte
nonce := raw[:]
s.generateNonce(nonce)
info.Nonce = string(nonce)
}
return info
} | go | func (s *Server) copyInfo() Info {
info := s.info
if info.ClientConnectURLs != nil {
info.ClientConnectURLs = make([]string, len(s.info.ClientConnectURLs))
copy(info.ClientConnectURLs, s.info.ClientConnectURLs)
}
if s.nonceRequired() {
// Nonce handling
var raw [nonceLen]byte
nonce := raw[:]
s.generateNonce(nonce)
info.Nonce = string(nonce)
}
return info
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"copyInfo",
"(",
")",
"Info",
"{",
"info",
":=",
"s",
".",
"info",
"\n",
"if",
"info",
".",
"ClientConnectURLs",
"!=",
"nil",
"{",
"info",
".",
"ClientConnectURLs",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"s",
".",
"info",
".",
"ClientConnectURLs",
")",
")",
"\n",
"copy",
"(",
"info",
".",
"ClientConnectURLs",
",",
"s",
".",
"info",
".",
"ClientConnectURLs",
")",
"\n",
"}",
"\n",
"if",
"s",
".",
"nonceRequired",
"(",
")",
"{",
"// Nonce handling",
"var",
"raw",
"[",
"nonceLen",
"]",
"byte",
"\n",
"nonce",
":=",
"raw",
"[",
":",
"]",
"\n",
"s",
".",
"generateNonce",
"(",
"nonce",
")",
"\n",
"info",
".",
"Nonce",
"=",
"string",
"(",
"nonce",
")",
"\n",
"}",
"\n",
"return",
"info",
"\n",
"}"
] | // Perform a conditional deep copy due to reference nature of ClientConnectURLs.
// If updates are made to Info, this function should be consulted and updated.
// Assume lock is held. | [
"Perform",
"a",
"conditional",
"deep",
"copy",
"due",
"to",
"reference",
"nature",
"of",
"ClientConnectURLs",
".",
"If",
"updates",
"are",
"made",
"to",
"Info",
"this",
"function",
"should",
"be",
"consulted",
"and",
"updated",
".",
"Assume",
"lock",
"is",
"held",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1436-L1450 |
164,094 | nats-io/gnatsd | server/server.go | tlsTimeout | func tlsTimeout(c *client, conn *tls.Conn) {
c.mu.Lock()
nc := c.nc
c.mu.Unlock()
// Check if already closed
if nc == nil {
return
}
cs := conn.ConnectionState()
if !cs.HandshakeComplete {
c.Errorf("TLS handshake timeout")
c.sendErr("Secure Connection - TLS Required")
c.closeConnection(TLSHandshakeError)
}
} | go | func tlsTimeout(c *client, conn *tls.Conn) {
c.mu.Lock()
nc := c.nc
c.mu.Unlock()
// Check if already closed
if nc == nil {
return
}
cs := conn.ConnectionState()
if !cs.HandshakeComplete {
c.Errorf("TLS handshake timeout")
c.sendErr("Secure Connection - TLS Required")
c.closeConnection(TLSHandshakeError)
}
} | [
"func",
"tlsTimeout",
"(",
"c",
"*",
"client",
",",
"conn",
"*",
"tls",
".",
"Conn",
")",
"{",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"nc",
":=",
"c",
".",
"nc",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"// Check if already closed",
"if",
"nc",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"cs",
":=",
"conn",
".",
"ConnectionState",
"(",
")",
"\n",
"if",
"!",
"cs",
".",
"HandshakeComplete",
"{",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"sendErr",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"closeConnection",
"(",
"TLSHandshakeError",
")",
"\n",
"}",
"\n",
"}"
] | // Handle closing down a connection when the handshake has timedout. | [
"Handle",
"closing",
"down",
"a",
"connection",
"when",
"the",
"handshake",
"has",
"timedout",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1664-L1678 |
164,095 | nats-io/gnatsd | server/server.go | tlsVersion | func tlsVersion(ver uint16) string {
switch ver {
case tls.VersionTLS10:
return "1.0"
case tls.VersionTLS11:
return "1.1"
case tls.VersionTLS12:
return "1.2"
}
return fmt.Sprintf("Unknown [%x]", ver)
} | go | func tlsVersion(ver uint16) string {
switch ver {
case tls.VersionTLS10:
return "1.0"
case tls.VersionTLS11:
return "1.1"
case tls.VersionTLS12:
return "1.2"
}
return fmt.Sprintf("Unknown [%x]", ver)
} | [
"func",
"tlsVersion",
"(",
"ver",
"uint16",
")",
"string",
"{",
"switch",
"ver",
"{",
"case",
"tls",
".",
"VersionTLS10",
":",
"return",
"\"",
"\"",
"\n",
"case",
"tls",
".",
"VersionTLS11",
":",
"return",
"\"",
"\"",
"\n",
"case",
"tls",
".",
"VersionTLS12",
":",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ver",
")",
"\n",
"}"
] | // Seems silly we have to write these | [
"Seems",
"silly",
"we",
"have",
"to",
"write",
"these"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1681-L1691 |
164,096 | nats-io/gnatsd | server/server.go | tlsCipher | func tlsCipher(cs uint16) string {
name, present := cipherMapByID[cs]
if present {
return name
}
return fmt.Sprintf("Unknown [%x]", cs)
} | go | func tlsCipher(cs uint16) string {
name, present := cipherMapByID[cs]
if present {
return name
}
return fmt.Sprintf("Unknown [%x]", cs)
} | [
"func",
"tlsCipher",
"(",
"cs",
"uint16",
")",
"string",
"{",
"name",
",",
"present",
":=",
"cipherMapByID",
"[",
"cs",
"]",
"\n",
"if",
"present",
"{",
"return",
"name",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cs",
")",
"\n",
"}"
] | // We use hex here so we don't need multiple versions | [
"We",
"use",
"hex",
"here",
"so",
"we",
"don",
"t",
"need",
"multiple",
"versions"
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1694-L1700 |
164,097 | nats-io/gnatsd | server/server.go | removeClient | func (s *Server) removeClient(c *client) {
// type is immutable, so can check without lock
switch c.kind {
case CLIENT:
c.mu.Lock()
cid := c.cid
updateProtoInfoCount := false
if c.kind == CLIENT && c.opts.Protocol >= ClientProtoInfo {
updateProtoInfoCount = true
}
c.mu.Unlock()
s.mu.Lock()
delete(s.clients, cid)
if updateProtoInfoCount {
s.cproto--
}
s.mu.Unlock()
case ROUTER:
s.removeRoute(c)
case GATEWAY:
s.removeRemoteGatewayConnection(c)
case LEAF:
s.removeLeafNodeConnection(c)
}
} | go | func (s *Server) removeClient(c *client) {
// type is immutable, so can check without lock
switch c.kind {
case CLIENT:
c.mu.Lock()
cid := c.cid
updateProtoInfoCount := false
if c.kind == CLIENT && c.opts.Protocol >= ClientProtoInfo {
updateProtoInfoCount = true
}
c.mu.Unlock()
s.mu.Lock()
delete(s.clients, cid)
if updateProtoInfoCount {
s.cproto--
}
s.mu.Unlock()
case ROUTER:
s.removeRoute(c)
case GATEWAY:
s.removeRemoteGatewayConnection(c)
case LEAF:
s.removeLeafNodeConnection(c)
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"removeClient",
"(",
"c",
"*",
"client",
")",
"{",
"// type is immutable, so can check without lock",
"switch",
"c",
".",
"kind",
"{",
"case",
"CLIENT",
":",
"c",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"cid",
":=",
"c",
".",
"cid",
"\n",
"updateProtoInfoCount",
":=",
"false",
"\n",
"if",
"c",
".",
"kind",
"==",
"CLIENT",
"&&",
"c",
".",
"opts",
".",
"Protocol",
">=",
"ClientProtoInfo",
"{",
"updateProtoInfoCount",
"=",
"true",
"\n",
"}",
"\n",
"c",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"s",
".",
"clients",
",",
"cid",
")",
"\n",
"if",
"updateProtoInfoCount",
"{",
"s",
".",
"cproto",
"--",
"\n",
"}",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"case",
"ROUTER",
":",
"s",
".",
"removeRoute",
"(",
"c",
")",
"\n",
"case",
"GATEWAY",
":",
"s",
".",
"removeRemoteGatewayConnection",
"(",
"c",
")",
"\n",
"case",
"LEAF",
":",
"s",
".",
"removeLeafNodeConnection",
"(",
"c",
")",
"\n",
"}",
"\n",
"}"
] | // Remove a client or route from our internal accounting. | [
"Remove",
"a",
"client",
"or",
"route",
"from",
"our",
"internal",
"accounting",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1703-L1728 |
164,098 | nats-io/gnatsd | server/server.go | NumRemotes | func (s *Server) NumRemotes() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.remotes)
} | go | func (s *Server) NumRemotes() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.remotes)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"NumRemotes",
"(",
")",
"int",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"len",
"(",
"s",
".",
"remotes",
")",
"\n",
"}"
] | // NumRemotes will report number of registered remotes. | [
"NumRemotes",
"will",
"report",
"number",
"of",
"registered",
"remotes",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1760-L1764 |
164,099 | nats-io/gnatsd | server/server.go | NumLeafNodes | func (s *Server) NumLeafNodes() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.leafs)
} | go | func (s *Server) NumLeafNodes() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.leafs)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"NumLeafNodes",
"(",
")",
"int",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"len",
"(",
"s",
".",
"leafs",
")",
"\n",
"}"
] | // NumLeafNodes will report number of leaf node connections. | [
"NumLeafNodes",
"will",
"report",
"number",
"of",
"leaf",
"node",
"connections",
"."
] | 7ebe2836016a033f11d9da712ed6a1abb95c06dd | https://github.com/nats-io/gnatsd/blob/7ebe2836016a033f11d9da712ed6a1abb95c06dd/server/server.go#L1767-L1771 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.