id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1
value | code stringlengths 52 85.5k | code_tokens listlengths 21 1.41k | docstring stringlengths 6 2.61k | docstring_tokens listlengths 3 215 | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
164,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",
... | // 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",
",",
"partiti... | // 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",
"QueryWatermarkOf... | 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_assig... | // 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",
"(",
... | // 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"... | // 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",
".",... | // 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",... | // 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",
"("... | // 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",
... | // 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... | // 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",
")",... | // 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",
"stringMa... | // 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",
")",
")",
... | // 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",
... | // 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",
","... | // 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",... | 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",
"=",
"... | // 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",
")",
"{",
"resul... | // 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",
")",
... | // 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",
"aft... | 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",
".... | // 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",
":=",
"&... | // 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",
",... | // 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",
",... | // 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",
":=",... | // 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... | 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",
... | // 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",
")... | // 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",
... | 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",
".",
... | // 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",
"ProduceCh... | 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",
".",
"S... | // 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",
"n... | 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",
".",
"p... | // 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",
"!=",
... | // 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",
"... | // 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",
... | // 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",
"}",
"els... | // 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",
... | // 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 ... | // 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",
".",
... | // 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... | // 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",
",",
"ni... | // 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... | // 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",
"m... | // 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",
"m... | // 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"... | // 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",
"... | // 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",
... | // 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",
".",... | // 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",
"."... | // 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",
"/... | // 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"... | // 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",
"=",
... | // 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",
... | // 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",
"==",
"\"",
"\"",
"{",... | // 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",
",",
"B... | // 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",
... | // 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",
... | // 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",... | // 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 ... | // 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",
".",... | // 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 a... | // 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",
... | // 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",
":=",
"cm... | // 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",
"{",
"}",
")",... | // 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",... | // 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",
... | // 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",
"(",
... | // 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",... | // 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",
"(",
")... | // 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",
"{",... | // 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",
... | // 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",
... | // 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"... | // 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",
"\"",
"\"",
",",
"Err... | // 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... | // 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",
"(",
"claim... | // 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",
"... | // 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",
"... | // 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",
".",
"shutdownEvent... | // 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",
"{... | // 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... | // 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",
"!=",... | // 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",
"[",
... | // 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",
",",
"l... | // 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",
"... | 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 cl... | // 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",
".",
"Version... | // 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",
... | // 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",
":=",
... | // 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 community queries yet
The top public SQL queries from the community will appear here once available.