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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
4,500
ligato/cn-infra
messaging/kafka/client/syncproducer.go
setProducerRequiredAcks
func setProducerRequiredAcks(cfg *Config) error { switch cfg.RequiredAcks { case NoResponse: cfg.ProducerConfig().Producer.RequiredAcks = sarama.NoResponse return nil case WaitForLocal: cfg.ProducerConfig().Producer.RequiredAcks = sarama.WaitForLocal return nil case WaitForAll: cfg.ProducerConfig().Producer.RequiredAcks = sarama.WaitForAll return nil default: return errors.New("Invalid RequiredAcks type") } }
go
func setProducerRequiredAcks(cfg *Config) error { switch cfg.RequiredAcks { case NoResponse: cfg.ProducerConfig().Producer.RequiredAcks = sarama.NoResponse return nil case WaitForLocal: cfg.ProducerConfig().Producer.RequiredAcks = sarama.WaitForLocal return nil case WaitForAll: cfg.ProducerConfig().Producer.RequiredAcks = sarama.WaitForAll return nil default: return errors.New("Invalid RequiredAcks type") } }
[ "func", "setProducerRequiredAcks", "(", "cfg", "*", "Config", ")", "error", "{", "switch", "cfg", ".", "RequiredAcks", "{", "case", "NoResponse", ":", "cfg", ".", "ProducerConfig", "(", ")", ".", "Producer", ".", "RequiredAcks", "=", "sarama", ".", "NoRespon...
// setProducerRequiredAcks set the RequiredAcks field for a producer
[ "setProducerRequiredAcks", "set", "the", "RequiredAcks", "field", "for", "a", "producer" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/syncproducer.go#L185-L199
4,501
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
NewSyncPublisher
func (conn *ProtoConnection) NewSyncPublisher(topic string) (messaging.ProtoPublisher, error) { return &protoSyncPublisherKafka{conn, topic}, nil }
go
func (conn *ProtoConnection) NewSyncPublisher(topic string) (messaging.ProtoPublisher, error) { return &protoSyncPublisherKafka{conn, topic}, nil }
[ "func", "(", "conn", "*", "ProtoConnection", ")", "NewSyncPublisher", "(", "topic", "string", ")", "(", "messaging", ".", "ProtoPublisher", ",", "error", ")", "{", "return", "&", "protoSyncPublisherKafka", "{", "conn", ",", "topic", "}", ",", "nil", "\n", ...
// NewSyncPublisher creates a new instance of protoSyncPublisherKafka that allows to publish sync kafka messages using common messaging API
[ "NewSyncPublisher", "creates", "a", "new", "instance", "of", "protoSyncPublisherKafka", "that", "allows", "to", "publish", "sync", "kafka", "messages", "using", "common", "messaging", "API" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L81-L83
4,502
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
NewAsyncPublisher
func (conn *ProtoConnection) NewAsyncPublisher(topic string, successClb func(messaging.ProtoMessage), errorClb func(messaging.ProtoMessageErr)) (messaging.ProtoPublisher, error) { return &protoAsyncPublisherKafka{conn, topic, successClb, errorClb}, nil }
go
func (conn *ProtoConnection) NewAsyncPublisher(topic string, successClb func(messaging.ProtoMessage), errorClb func(messaging.ProtoMessageErr)) (messaging.ProtoPublisher, error) { return &protoAsyncPublisherKafka{conn, topic, successClb, errorClb}, nil }
[ "func", "(", "conn", "*", "ProtoConnection", ")", "NewAsyncPublisher", "(", "topic", "string", ",", "successClb", "func", "(", "messaging", ".", "ProtoMessage", ")", ",", "errorClb", "func", "(", "messaging", ".", "ProtoMessageErr", ")", ")", "(", "messaging",...
// NewAsyncPublisher creates a new instance of protoAsyncPublisherKafka that allows to publish sync kafka messages using common messaging API
[ "NewAsyncPublisher", "creates", "a", "new", "instance", "of", "protoAsyncPublisherKafka", "that", "allows", "to", "publish", "sync", "kafka", "messages", "using", "common", "messaging", "API" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L86-L88
4,503
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
NewSyncPublisherToPartition
func (conn *ProtoManualConnection) NewSyncPublisherToPartition(topic string, partition int32) (messaging.ProtoPublisher, error) { return &protoManualSyncPublisherKafka{conn, topic, partition}, nil }
go
func (conn *ProtoManualConnection) NewSyncPublisherToPartition(topic string, partition int32) (messaging.ProtoPublisher, error) { return &protoManualSyncPublisherKafka{conn, topic, partition}, nil }
[ "func", "(", "conn", "*", "ProtoManualConnection", ")", "NewSyncPublisherToPartition", "(", "topic", "string", ",", "partition", "int32", ")", "(", "messaging", ".", "ProtoPublisher", ",", "error", ")", "{", "return", "&", "protoManualSyncPublisherKafka", "{", "co...
// NewSyncPublisherToPartition creates a new instance of protoManualSyncPublisherKafka that allows to publish sync kafka messages using common messaging API
[ "NewSyncPublisherToPartition", "creates", "a", "new", "instance", "of", "protoManualSyncPublisherKafka", "that", "allows", "to", "publish", "sync", "kafka", "messages", "using", "common", "messaging", "API" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L91-L93
4,504
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
NewAsyncPublisherToPartition
func (conn *ProtoManualConnection) NewAsyncPublisherToPartition(topic string, partition int32, successClb func(messaging.ProtoMessage), errorClb func(messaging.ProtoMessageErr)) (messaging.ProtoPublisher, error) { return &protoManualAsyncPublisherKafka{conn, topic, partition, successClb, errorClb}, nil }
go
func (conn *ProtoManualConnection) NewAsyncPublisherToPartition(topic string, partition int32, successClb func(messaging.ProtoMessage), errorClb func(messaging.ProtoMessageErr)) (messaging.ProtoPublisher, error) { return &protoManualAsyncPublisherKafka{conn, topic, partition, successClb, errorClb}, nil }
[ "func", "(", "conn", "*", "ProtoManualConnection", ")", "NewAsyncPublisherToPartition", "(", "topic", "string", ",", "partition", "int32", ",", "successClb", "func", "(", "messaging", ".", "ProtoMessage", ")", ",", "errorClb", "func", "(", "messaging", ".", "Pro...
// NewAsyncPublisherToPartition creates a new instance of protoManualAsyncPublisherKafka that allows to publish sync kafka // messages using common messaging API.
[ "NewAsyncPublisherToPartition", "creates", "a", "new", "instance", "of", "protoManualAsyncPublisherKafka", "that", "allows", "to", "publish", "sync", "kafka", "messages", "using", "common", "messaging", "API", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L97-L99
4,505
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
Watch
func (conn *ProtoConnection) Watch(msgClb func(messaging.ProtoMessage), topics ...string) error { return conn.ConsumeTopic(msgClb, topics...) }
go
func (conn *ProtoConnection) Watch(msgClb func(messaging.ProtoMessage), topics ...string) error { return conn.ConsumeTopic(msgClb, topics...) }
[ "func", "(", "conn", "*", "ProtoConnection", ")", "Watch", "(", "msgClb", "func", "(", "messaging", ".", "ProtoMessage", ")", ",", "topics", "...", "string", ")", "error", "{", "return", "conn", ".", "ConsumeTopic", "(", "msgClb", ",", "topics", "...", "...
// Watch is an alias for ConsumeTopic method. The alias was added in order to conform to messaging.Mux interface.
[ "Watch", "is", "an", "alias", "for", "ConsumeTopic", "method", ".", "The", "alias", "was", "added", "in", "order", "to", "conform", "to", "messaging", ".", "Mux", "interface", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L102-L104
4,506
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
ConsumeTopic
func (conn *ProtoConnection) ConsumeTopic(msgClb func(messaging.ProtoMessage), topics ...string) error { conn.multiplexer.rwlock.Lock() defer conn.multiplexer.rwlock.Unlock() if conn.multiplexer.started { return fmt.Errorf("ConsumeTopic can be called only if the multiplexer has not been started yet") } byteClb := func(bm *client.ConsumerMessage) { pm := client.NewProtoConsumerMessage(bm, conn.serializer) msgClb(pm) } for _, topic := range topics { // check if we have already consumed the topic var found bool var subs *consumerSubscription LoopSubs: for _, subscription := range conn.multiplexer.mapping { if subscription.manual == true { // do not mix dynamic and manual mode continue } if subscription.topic == topic { found = true subs = subscription break LoopSubs } } if !found { subs = &consumerSubscription{ manual: false, // non-manual example topic: topic, connectionName: conn.name, byteConsMsg: byteClb, } // subscribe new topic conn.multiplexer.mapping = append(conn.multiplexer.mapping, subs) } // add subscription to consumerList subs.byteConsMsg = byteClb } return nil }
go
func (conn *ProtoConnection) ConsumeTopic(msgClb func(messaging.ProtoMessage), topics ...string) error { conn.multiplexer.rwlock.Lock() defer conn.multiplexer.rwlock.Unlock() if conn.multiplexer.started { return fmt.Errorf("ConsumeTopic can be called only if the multiplexer has not been started yet") } byteClb := func(bm *client.ConsumerMessage) { pm := client.NewProtoConsumerMessage(bm, conn.serializer) msgClb(pm) } for _, topic := range topics { // check if we have already consumed the topic var found bool var subs *consumerSubscription LoopSubs: for _, subscription := range conn.multiplexer.mapping { if subscription.manual == true { // do not mix dynamic and manual mode continue } if subscription.topic == topic { found = true subs = subscription break LoopSubs } } if !found { subs = &consumerSubscription{ manual: false, // non-manual example topic: topic, connectionName: conn.name, byteConsMsg: byteClb, } // subscribe new topic conn.multiplexer.mapping = append(conn.multiplexer.mapping, subs) } // add subscription to consumerList subs.byteConsMsg = byteClb } return nil }
[ "func", "(", "conn", "*", "ProtoConnection", ")", "ConsumeTopic", "(", "msgClb", "func", "(", "messaging", ".", "ProtoMessage", ")", ",", "topics", "...", "string", ")", "error", "{", "conn", ".", "multiplexer", ".", "rwlock", ".", "Lock", "(", ")", "\n"...
// ConsumeTopic is called to start consuming given topics. // Function can be called until the multiplexer is started, it returns an error otherwise. // The provided channel should be buffered, otherwise messages might be lost.
[ "ConsumeTopic", "is", "called", "to", "start", "consuming", "given", "topics", ".", "Function", "can", "be", "called", "until", "the", "multiplexer", "is", "started", "it", "returns", "an", "error", "otherwise", ".", "The", "provided", "channel", "should", "be...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L109-L155
4,507
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
WatchPartition
func (conn *ProtoManualConnection) WatchPartition(msgClb func(messaging.ProtoMessage), topic string, partition int32, offset int64) error { return conn.ConsumePartition(msgClb, topic, partition, offset) }
go
func (conn *ProtoManualConnection) WatchPartition(msgClb func(messaging.ProtoMessage), topic string, partition int32, offset int64) error { return conn.ConsumePartition(msgClb, topic, partition, offset) }
[ "func", "(", "conn", "*", "ProtoManualConnection", ")", "WatchPartition", "(", "msgClb", "func", "(", "messaging", ".", "ProtoMessage", ")", ",", "topic", "string", ",", "partition", "int32", ",", "offset", "int64", ")", "error", "{", "return", "conn", ".", ...
// WatchPartition is an alias for ConsumePartition method. The alias was added in order to conform to // messaging.Mux interface.
[ "WatchPartition", "is", "an", "alias", "for", "ConsumePartition", "method", ".", "The", "alias", "was", "added", "in", "order", "to", "conform", "to", "messaging", ".", "Mux", "interface", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L159-L161
4,508
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
StopWatchPartition
func (conn *ProtoConnectionFields) StopWatchPartition(topic string, partition int32, offset int64) error { return conn.StopConsumingPartition(topic, partition, offset) }
go
func (conn *ProtoConnectionFields) StopWatchPartition(topic string, partition int32, offset int64) error { return conn.StopConsumingPartition(topic, partition, offset) }
[ "func", "(", "conn", "*", "ProtoConnectionFields", ")", "StopWatchPartition", "(", "topic", "string", ",", "partition", "int32", ",", "offset", "int64", ")", "error", "{", "return", "conn", ".", "StopConsumingPartition", "(", "topic", ",", "partition", ",", "o...
// StopWatchPartition is an alias for StopConsumingPartition method. The alias was added in order to conform to messaging.Mux interface.
[ "StopWatchPartition", "is", "an", "alias", "for", "StopConsumingPartition", "method", ".", "The", "alias", "was", "added", "in", "order", "to", "conform", "to", "messaging", ".", "Mux", "interface", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L254-L256
4,509
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
StopConsumingPartition
func (conn *ProtoConnectionFields) StopConsumingPartition(topic string, partition int32, offset int64) error { return conn.multiplexer.stopConsumingPartition(topic, partition, offset, conn.name) }
go
func (conn *ProtoConnectionFields) StopConsumingPartition(topic string, partition int32, offset int64) error { return conn.multiplexer.stopConsumingPartition(topic, partition, offset, conn.name) }
[ "func", "(", "conn", "*", "ProtoConnectionFields", ")", "StopConsumingPartition", "(", "topic", "string", ",", "partition", "int32", ",", "offset", "int64", ")", "error", "{", "return", "conn", ".", "multiplexer", ".", "stopConsumingPartition", "(", "topic", ","...
// StopConsumingPartition cancels the previously created subscription for consuming the topic, partition and offset
[ "StopConsumingPartition", "cancels", "the", "previously", "created", "subscription", "for", "consuming", "the", "topic", "partition", "and", "offset" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L259-L261
4,510
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
sendSyncMessage
func (conn *ProtoConnectionFields) sendSyncMessage(topic string, partition int32, key string, value proto.Message, manualMode bool) (offset int64, err error) { data, err := conn.serializer.Marshal(value) if err != nil { return 0, err } if manualMode { msg, err := conn.multiplexer.manSyncProducer.SendMsgToPartition(topic, partition, sarama.StringEncoder(key), sarama.ByteEncoder(data)) if err != nil { return 0, err } return msg.Offset, err } msg, err := conn.multiplexer.hashSyncProducer.SendMsgToPartition(topic, partition, sarama.StringEncoder(key), sarama.ByteEncoder(data)) if err != nil { return 0, err } return msg.Offset, err }
go
func (conn *ProtoConnectionFields) sendSyncMessage(topic string, partition int32, key string, value proto.Message, manualMode bool) (offset int64, err error) { data, err := conn.serializer.Marshal(value) if err != nil { return 0, err } if manualMode { msg, err := conn.multiplexer.manSyncProducer.SendMsgToPartition(topic, partition, sarama.StringEncoder(key), sarama.ByteEncoder(data)) if err != nil { return 0, err } return msg.Offset, err } msg, err := conn.multiplexer.hashSyncProducer.SendMsgToPartition(topic, partition, sarama.StringEncoder(key), sarama.ByteEncoder(data)) if err != nil { return 0, err } return msg.Offset, err }
[ "func", "(", "conn", "*", "ProtoConnectionFields", ")", "sendSyncMessage", "(", "topic", "string", ",", "partition", "int32", ",", "key", "string", ",", "value", "proto", ".", "Message", ",", "manualMode", "bool", ")", "(", "offset", "int64", ",", "err", "...
// sendSyncMessage sends a message using the sync API. If manual mode is chosen, the appropriate producer will be used.
[ "sendSyncMessage", "sends", "a", "message", "using", "the", "sync", "API", ".", "If", "manual", "mode", "is", "chosen", "the", "appropriate", "producer", "will", "be", "used", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L310-L328
4,511
ligato/cn-infra
messaging/kafka/mux/proto_connection.go
sendAsyncMessage
func (conn *ProtoConnectionFields) sendAsyncMessage(topic string, partition int32, key string, value proto.Message, manualMode bool, meta interface{}, successClb func(messaging.ProtoMessage), errClb func(messaging.ProtoMessageErr)) error { data, err := conn.serializer.Marshal(value) if err != nil { return err } succByteClb := func(msg *client.ProducerMessage) { protoMsg := &client.ProtoProducerMessage{ ProducerMessage: msg, Serializer: conn.serializer, } successClb(protoMsg) } errByteClb := func(msg *client.ProducerError) { protoMsg := &client.ProtoProducerMessageErr{ ProtoProducerMessage: &client.ProtoProducerMessage{ ProducerMessage: msg.ProducerMessage, Serializer: conn.serializer, }, Err: msg.Err, } errClb(protoMsg) } if manualMode { auxMeta := &asyncMeta{successClb: succByteClb, errorClb: errByteClb, usersMeta: meta} conn.multiplexer.manAsyncProducer.SendMsgToPartition(topic, partition, sarama.StringEncoder(key), sarama.ByteEncoder(data), auxMeta) return nil } auxMeta := &asyncMeta{successClb: succByteClb, errorClb: errByteClb, usersMeta: meta} conn.multiplexer.hashAsyncProducer.SendMsgToPartition(topic, partition, sarama.StringEncoder(key), sarama.ByteEncoder(data), auxMeta) return nil }
go
func (conn *ProtoConnectionFields) sendAsyncMessage(topic string, partition int32, key string, value proto.Message, manualMode bool, meta interface{}, successClb func(messaging.ProtoMessage), errClb func(messaging.ProtoMessageErr)) error { data, err := conn.serializer.Marshal(value) if err != nil { return err } succByteClb := func(msg *client.ProducerMessage) { protoMsg := &client.ProtoProducerMessage{ ProducerMessage: msg, Serializer: conn.serializer, } successClb(protoMsg) } errByteClb := func(msg *client.ProducerError) { protoMsg := &client.ProtoProducerMessageErr{ ProtoProducerMessage: &client.ProtoProducerMessage{ ProducerMessage: msg.ProducerMessage, Serializer: conn.serializer, }, Err: msg.Err, } errClb(protoMsg) } if manualMode { auxMeta := &asyncMeta{successClb: succByteClb, errorClb: errByteClb, usersMeta: meta} conn.multiplexer.manAsyncProducer.SendMsgToPartition(topic, partition, sarama.StringEncoder(key), sarama.ByteEncoder(data), auxMeta) return nil } auxMeta := &asyncMeta{successClb: succByteClb, errorClb: errByteClb, usersMeta: meta} conn.multiplexer.hashAsyncProducer.SendMsgToPartition(topic, partition, sarama.StringEncoder(key), sarama.ByteEncoder(data), auxMeta) return nil }
[ "func", "(", "conn", "*", "ProtoConnectionFields", ")", "sendAsyncMessage", "(", "topic", "string", ",", "partition", "int32", ",", "key", "string", ",", "value", "proto", ".", "Message", ",", "manualMode", "bool", ",", "meta", "interface", "{", "}", ",", ...
// sendAsyncMessage sends a message using the async API. If manual mode is chosen, the appropriate producer will be used.
[ "sendAsyncMessage", "sends", "a", "message", "using", "the", "async", "API", ".", "If", "manual", "mode", "is", "chosen", "the", "appropriate", "producer", "will", "be", "used", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/proto_connection.go#L331-L364
4,512
ligato/cn-infra
rpc/grpc/auth.go
Authenticate
func (a Authenticator) Authenticate(ctx context.Context) (newCtx context.Context, err error) { defer func() { if err == nil { // Store user metadata userMD := &UserMetadata{ ID: a.Username, } newCtx = context.WithValue(newCtx, userMDKey{}, userMD) } }() err = a.tryTLSAuth(ctx) if err == nil { return ctx, nil } newCtx, err = a.tryTokenAuth(ctx) if err == nil { return newCtx, nil } return a.tryBasicAuth(ctx) }
go
func (a Authenticator) Authenticate(ctx context.Context) (newCtx context.Context, err error) { defer func() { if err == nil { // Store user metadata userMD := &UserMetadata{ ID: a.Username, } newCtx = context.WithValue(newCtx, userMDKey{}, userMD) } }() err = a.tryTLSAuth(ctx) if err == nil { return ctx, nil } newCtx, err = a.tryTokenAuth(ctx) if err == nil { return newCtx, nil } return a.tryBasicAuth(ctx) }
[ "func", "(", "a", "Authenticator", ")", "Authenticate", "(", "ctx", "context", ".", "Context", ")", "(", "newCtx", "context", ".", "Context", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "err", "==", "nil", "{", "// Store user m...
// Authenticate checks that a token exists and is valid. It stores the user // metadata in the returned context and removes the token from the context.
[ "Authenticate", "checks", "that", "a", "token", "exists", "and", "is", "valid", ".", "It", "stores", "the", "user", "metadata", "in", "the", "returned", "context", "and", "removes", "the", "token", "from", "the", "context", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/grpc/auth.go#L38-L60
4,513
ligato/cn-infra
rpc/grpc/auth.go
GetUserMetadata
func GetUserMetadata(ctx context.Context) (*UserMetadata, bool) { userMD := ctx.Value(userMDKey{}) switch md := userMD.(type) { case *UserMetadata: return md, true default: return nil, false } }
go
func GetUserMetadata(ctx context.Context) (*UserMetadata, bool) { userMD := ctx.Value(userMDKey{}) switch md := userMD.(type) { case *UserMetadata: return md, true default: return nil, false } }
[ "func", "GetUserMetadata", "(", "ctx", "context", ".", "Context", ")", "(", "*", "UserMetadata", ",", "bool", ")", "{", "userMD", ":=", "ctx", ".", "Value", "(", "userMDKey", "{", "}", ")", "\n\n", "switch", "md", ":=", "userMD", ".", "(", "type", ")...
// GetUserMetadata can be used to extract user metadata stored in a context.
[ "GetUserMetadata", "can", "be", "used", "to", "extract", "user", "metadata", "stored", "in", "a", "context", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/grpc/auth.go#L167-L176
4,514
ligato/cn-infra
db/keyval/filedb/broker.go
Put
func (pdb *BrokerWatcher) Put(key string, data []byte, opts ...datasync.PutOption) error { return pdb.Client.Put(pdb.prefixKey(key), data, opts...) }
go
func (pdb *BrokerWatcher) Put(key string, data []byte, opts ...datasync.PutOption) error { return pdb.Client.Put(pdb.prefixKey(key), data, opts...) }
[ "func", "(", "pdb", "*", "BrokerWatcher", ")", "Put", "(", "key", "string", ",", "data", "[", "]", "byte", ",", "opts", "...", "datasync", ".", "PutOption", ")", "error", "{", "return", "pdb", ".", "Client", ".", "Put", "(", "pdb", ".", "prefixKey", ...
// Put calls client's 'Put' method
[ "Put", "calls", "client", "s", "Put", "method" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/broker.go#L19-L21
4,515
ligato/cn-infra
db/keyval/filedb/broker.go
GetValue
func (pdb *BrokerWatcher) GetValue(key string) (data []byte, found bool, revision int64, err error) { return pdb.Client.GetValue(pdb.prefixKey(key)) }
go
func (pdb *BrokerWatcher) GetValue(key string) (data []byte, found bool, revision int64, err error) { return pdb.Client.GetValue(pdb.prefixKey(key)) }
[ "func", "(", "pdb", "*", "BrokerWatcher", ")", "GetValue", "(", "key", "string", ")", "(", "data", "[", "]", "byte", ",", "found", "bool", ",", "revision", "int64", ",", "err", "error", ")", "{", "return", "pdb", ".", "Client", ".", "GetValue", "(", ...
// GetValue calls client's 'GetValue' method
[ "GetValue", "calls", "client", "s", "GetValue", "method" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/broker.go#L29-L31
4,516
ligato/cn-infra
db/keyval/filedb/broker.go
Delete
func (pdb *BrokerWatcher) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) { return pdb.Client.Delete(pdb.prefixKey(key), opts...) }
go
func (pdb *BrokerWatcher) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) { return pdb.Client.Delete(pdb.prefixKey(key), opts...) }
[ "func", "(", "pdb", "*", "BrokerWatcher", ")", "Delete", "(", "key", "string", ",", "opts", "...", "datasync", ".", "DelOption", ")", "(", "existed", "bool", ",", "err", "error", ")", "{", "return", "pdb", ".", "Client", ".", "Delete", "(", "pdb", "....
// Delete calls client's 'Delete' method
[ "Delete", "calls", "client", "s", "Delete", "method" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/broker.go#L34-L36
4,517
ligato/cn-infra
db/keyval/filedb/broker.go
ListValues
func (pdb *BrokerWatcher) ListValues(key string) (keyval.BytesKeyValIterator, error) { keyValues := pdb.db.GetDataForPrefix(pdb.prefixKey(key)) data := make([]*decoder.FileDataEntry, 0, len(keyValues)) for _, entry := range keyValues { data = append(data, &decoder.FileDataEntry{ Key: strings.TrimPrefix(entry.Key, pdb.prefix), Value: entry.Value, }) } return &bytesKeyValIterator{len: len(data), data: data}, nil }
go
func (pdb *BrokerWatcher) ListValues(key string) (keyval.BytesKeyValIterator, error) { keyValues := pdb.db.GetDataForPrefix(pdb.prefixKey(key)) data := make([]*decoder.FileDataEntry, 0, len(keyValues)) for _, entry := range keyValues { data = append(data, &decoder.FileDataEntry{ Key: strings.TrimPrefix(entry.Key, pdb.prefix), Value: entry.Value, }) } return &bytesKeyValIterator{len: len(data), data: data}, nil }
[ "func", "(", "pdb", "*", "BrokerWatcher", ")", "ListValues", "(", "key", "string", ")", "(", "keyval", ".", "BytesKeyValIterator", ",", "error", ")", "{", "keyValues", ":=", "pdb", ".", "db", ".", "GetDataForPrefix", "(", "pdb", ".", "prefixKey", "(", "k...
// ListValues returns a list of all database values for given key
[ "ListValues", "returns", "a", "list", "of", "all", "database", "values", "for", "given", "key" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/broker.go#L39-L49
4,518
ligato/cn-infra
db/keyval/filedb/broker.go
ListKeys
func (pdb *BrokerWatcher) ListKeys(prefix string) (keyval.BytesKeyIterator, error) { entries := pdb.Client.db.GetDataForPrefix(prefix) var keys []string for _, entry := range entries { keys = append(keys, entry.Key) } return &bytesKeyIterator{len: len(keys), keys: keys, prefix: pdb.prefix}, nil }
go
func (pdb *BrokerWatcher) ListKeys(prefix string) (keyval.BytesKeyIterator, error) { entries := pdb.Client.db.GetDataForPrefix(prefix) var keys []string for _, entry := range entries { keys = append(keys, entry.Key) } return &bytesKeyIterator{len: len(keys), keys: keys, prefix: pdb.prefix}, nil }
[ "func", "(", "pdb", "*", "BrokerWatcher", ")", "ListKeys", "(", "prefix", "string", ")", "(", "keyval", ".", "BytesKeyIterator", ",", "error", ")", "{", "entries", ":=", "pdb", ".", "Client", ".", "db", ".", "GetDataForPrefix", "(", "prefix", ")", "\n", ...
// ListKeys returns a list of all database keys for given prefix
[ "ListKeys", "returns", "a", "list", "of", "all", "database", "keys", "for", "given", "prefix" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/broker.go#L52-L59
4,519
ligato/cn-infra
examples/tutorials/06_plugin_lookup/main.go
New
func New() *Agent { hw := &HelloWorld{} hu := &HelloUniverse{} hw.Universe = hu hu.World = hw return &Agent{ Hu: hu, Hw: hw, } }
go
func New() *Agent { hw := &HelloWorld{} hu := &HelloUniverse{} hw.Universe = hu hu.World = hw return &Agent{ Hu: hu, Hw: hw, } }
[ "func", "New", "(", ")", "*", "Agent", "{", "hw", ":=", "&", "HelloWorld", "{", "}", "\n", "hu", ":=", "&", "HelloUniverse", "{", "}", "\n\n", "hw", ".", "Universe", "=", "hu", "\n", "hu", ".", "World", "=", "hw", "\n\n", "return", "&", "Agent", ...
// New returns top-level plugin object with defined plugins and their dependencies
[ "New", "returns", "top", "-", "level", "plugin", "object", "with", "defined", "plugins", "and", "their", "dependencies" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/tutorials/06_plugin_lookup/main.go#L55-L66
4,520
ligato/cn-infra
rpc/rest/plugin_impl_rest.go
Init
func (p *Plugin) Init() (err error) { if p.Config == nil { p.Config = DefaultConfig() } if err := PluginConfig(p.Cfg, p.Config, p.PluginName); err != nil { return err } // if there is no injected authenticator and there are credentials defined in the config file // instantiate staticAuthenticator otherwise do not use basic Auth if p.Authenticator == nil && len(p.Config.ClientBasicAuth) > 0 { p.Authenticator, err = newStaticAuthenticator(p.Config.ClientBasicAuth) if err != nil { return err } } p.mx = mux.NewRouter() p.formatter = render.New(render.Options{ IndentJSON: true, }) // Enable authentication if defined by config if p.EnableTokenAuth { p.Log.Info("Token authentication for HTTP enabled") p.auth = security.NewAuthenticator(p.mx, &security.Settings{ Users: p.Users, ExpTime: p.TokenExpiration, Cost: p.PasswordHashCost, Signature: p.TokenSignature, }, p.Log) } return err }
go
func (p *Plugin) Init() (err error) { if p.Config == nil { p.Config = DefaultConfig() } if err := PluginConfig(p.Cfg, p.Config, p.PluginName); err != nil { return err } // if there is no injected authenticator and there are credentials defined in the config file // instantiate staticAuthenticator otherwise do not use basic Auth if p.Authenticator == nil && len(p.Config.ClientBasicAuth) > 0 { p.Authenticator, err = newStaticAuthenticator(p.Config.ClientBasicAuth) if err != nil { return err } } p.mx = mux.NewRouter() p.formatter = render.New(render.Options{ IndentJSON: true, }) // Enable authentication if defined by config if p.EnableTokenAuth { p.Log.Info("Token authentication for HTTP enabled") p.auth = security.NewAuthenticator(p.mx, &security.Settings{ Users: p.Users, ExpTime: p.TokenExpiration, Cost: p.PasswordHashCost, Signature: p.TokenSignature, }, p.Log) } return err }
[ "func", "(", "p", "*", "Plugin", ")", "Init", "(", ")", "(", "err", "error", ")", "{", "if", "p", ".", "Config", "==", "nil", "{", "p", ".", "Config", "=", "DefaultConfig", "(", ")", "\n", "}", "\n", "if", "err", ":=", "PluginConfig", "(", "p",...
// Init is the plugin entry point called by Agent Core // - It prepares Gorilla MUX HTTP Router
[ "Init", "is", "the", "plugin", "entry", "point", "called", "by", "Agent", "Core", "-", "It", "prepares", "Gorilla", "MUX", "HTTP", "Router" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/plugin_impl_rest.go#L55-L89
4,521
ligato/cn-infra
rpc/rest/plugin_impl_rest.go
AfterInit
func (p *Plugin) AfterInit() (err error) { cfgCopy := *p.Config var handler http.Handler = p.mx if p.Authenticator != nil { handler = auth(handler, p.Authenticator) } p.server, err = ListenAndServe(cfgCopy, handler) if err != nil { return err } if cfgCopy.UseHTTPS() { p.Log.Info("Listening on https://", cfgCopy.Endpoint) } else { p.Log.Info("Listening on http://", cfgCopy.Endpoint) } return nil }
go
func (p *Plugin) AfterInit() (err error) { cfgCopy := *p.Config var handler http.Handler = p.mx if p.Authenticator != nil { handler = auth(handler, p.Authenticator) } p.server, err = ListenAndServe(cfgCopy, handler) if err != nil { return err } if cfgCopy.UseHTTPS() { p.Log.Info("Listening on https://", cfgCopy.Endpoint) } else { p.Log.Info("Listening on http://", cfgCopy.Endpoint) } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "AfterInit", "(", ")", "(", "err", "error", ")", "{", "cfgCopy", ":=", "*", "p", ".", "Config", "\n\n", "var", "handler", "http", ".", "Handler", "=", "p", ".", "mx", "\n", "if", "p", ".", "Authenticator", "!...
// AfterInit starts the HTTP server.
[ "AfterInit", "starts", "the", "HTTP", "server", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/plugin_impl_rest.go#L92-L112
4,522
ligato/cn-infra
rpc/rest/plugin_impl_rest.go
RegisterPermissionGroup
func (p *Plugin) RegisterPermissionGroup(group ...*access.PermissionGroup) { if p.Config.EnableTokenAuth { p.Log.Debugf("Registering permission group(s): %s", group) p.auth.AddPermissionGroup(group...) } }
go
func (p *Plugin) RegisterPermissionGroup(group ...*access.PermissionGroup) { if p.Config.EnableTokenAuth { p.Log.Debugf("Registering permission group(s): %s", group) p.auth.AddPermissionGroup(group...) } }
[ "func", "(", "p", "*", "Plugin", ")", "RegisterPermissionGroup", "(", "group", "...", "*", "access", ".", "PermissionGroup", ")", "{", "if", "p", ".", "Config", ".", "EnableTokenAuth", "{", "p", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "group",...
// RegisterPermissionGroup adds new permission group if token authentication is enabled
[ "RegisterPermissionGroup", "adds", "new", "permission", "group", "if", "token", "authentication", "is", "enabled" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/plugin_impl_rest.go#L125-L130
4,523
ligato/cn-infra
rpc/rest/plugin_impl_rest.go
GetPort
func (p *Plugin) GetPort() int { if p.Config != nil { return p.Config.GetPort() } return 0 }
go
func (p *Plugin) GetPort() int { if p.Config != nil { return p.Config.GetPort() } return 0 }
[ "func", "(", "p", "*", "Plugin", ")", "GetPort", "(", ")", "int", "{", "if", "p", ".", "Config", "!=", "nil", "{", "return", "p", ".", "Config", ".", "GetPort", "(", ")", "\n", "}", "\n", "return", "0", "\n", "}" ]
// GetPort returns plugin configuration port
[ "GetPort", "returns", "plugin", "configuration", "port" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/plugin_impl_rest.go#L133-L138
4,524
ligato/cn-infra
datasync/syncbase/watcher.go
Watch
func (adapter *Registry) Watch(resyncName string, changeChan chan datasync.ChangeEvent, resyncChan chan datasync.ResyncEvent, keyPrefixes ...string) (datasync.WatchRegistration, error) { adapter.access.Lock() defer adapter.access.Unlock() if _, found := adapter.subscriptions[resyncName]; found { return nil, errors.New("Already watching " + resyncName) } adapter.subscriptions[resyncName] = &Subscription{ ResyncName: resyncName, ChangeChan: changeChan, ResyncChan: resyncChan, CloseChan: make(chan string), KeyPrefixes: keyPrefixes, } return &WatchDataReg{resyncName, adapter}, nil }
go
func (adapter *Registry) Watch(resyncName string, changeChan chan datasync.ChangeEvent, resyncChan chan datasync.ResyncEvent, keyPrefixes ...string) (datasync.WatchRegistration, error) { adapter.access.Lock() defer adapter.access.Unlock() if _, found := adapter.subscriptions[resyncName]; found { return nil, errors.New("Already watching " + resyncName) } adapter.subscriptions[resyncName] = &Subscription{ ResyncName: resyncName, ChangeChan: changeChan, ResyncChan: resyncChan, CloseChan: make(chan string), KeyPrefixes: keyPrefixes, } return &WatchDataReg{resyncName, adapter}, nil }
[ "func", "(", "adapter", "*", "Registry", ")", "Watch", "(", "resyncName", "string", ",", "changeChan", "chan", "datasync", ".", "ChangeEvent", ",", "resyncChan", "chan", "datasync", ".", "ResyncEvent", ",", "keyPrefixes", "...", "string", ")", "(", "datasync",...
// Watch only appends channels.
[ "Watch", "only", "appends", "channels", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/watcher.go#L79-L98
4,525
ligato/cn-infra
datasync/syncbase/watcher.go
PropagateChanges
func (adapter *Registry) PropagateChanges(ctx context.Context, txData map[string]datasync.ChangeValue) error { var events []func(done chan error) for _, sub := range adapter.subscriptions { var changes []datasync.ProtoWatchResp for _, prefix := range sub.KeyPrefixes { for key, val := range txData { if !strings.HasPrefix(key, prefix) { continue } var ( prev datasync.KeyVal curRev int64 ) if val.GetChangeType() == datasync.Delete { if _, prev = adapter.lastRev.Del(key); prev != nil { curRev = prev.GetRevision() + 1 } else { continue } } else { _, prev, curRev = adapter.lastRev.Put(key, val) } changes = append(changes, &ChangeResp{ Key: key, ChangeType: val.GetChangeType(), CurrVal: val, CurrRev: curRev, PrevVal: prev, }) } } if len(changes) > 0 { sendTo := func(sub *Subscription) func(done chan error) { return func(done chan error) { sub.ChangeChan <- &ChangeEvent{ ctx: ctx, Changes: changes, delegate: &DoneChannel{done}, } } } events = append(events, sendTo(sub)) } } done := make(chan error, 1) go AggregateDone(events, done) select { case err := <-done: if err != nil { return err } case <-time.After(PropagateChangesTimeout): logrus.DefaultLogger().Warnf("Timeout of aggregated data-change callbacks (%v)", PropagateChangesTimeout) } return nil }
go
func (adapter *Registry) PropagateChanges(ctx context.Context, txData map[string]datasync.ChangeValue) error { var events []func(done chan error) for _, sub := range adapter.subscriptions { var changes []datasync.ProtoWatchResp for _, prefix := range sub.KeyPrefixes { for key, val := range txData { if !strings.HasPrefix(key, prefix) { continue } var ( prev datasync.KeyVal curRev int64 ) if val.GetChangeType() == datasync.Delete { if _, prev = adapter.lastRev.Del(key); prev != nil { curRev = prev.GetRevision() + 1 } else { continue } } else { _, prev, curRev = adapter.lastRev.Put(key, val) } changes = append(changes, &ChangeResp{ Key: key, ChangeType: val.GetChangeType(), CurrVal: val, CurrRev: curRev, PrevVal: prev, }) } } if len(changes) > 0 { sendTo := func(sub *Subscription) func(done chan error) { return func(done chan error) { sub.ChangeChan <- &ChangeEvent{ ctx: ctx, Changes: changes, delegate: &DoneChannel{done}, } } } events = append(events, sendTo(sub)) } } done := make(chan error, 1) go AggregateDone(events, done) select { case err := <-done: if err != nil { return err } case <-time.After(PropagateChangesTimeout): logrus.DefaultLogger().Warnf("Timeout of aggregated data-change callbacks (%v)", PropagateChangesTimeout) } return nil }
[ "func", "(", "adapter", "*", "Registry", ")", "PropagateChanges", "(", "ctx", "context", ".", "Context", ",", "txData", "map", "[", "string", "]", "datasync", ".", "ChangeValue", ")", "error", "{", "var", "events", "[", "]", "func", "(", "done", "chan", ...
// PropagateChanges fills registered channels with the data.
[ "PropagateChanges", "fills", "registered", "channels", "with", "the", "data", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/watcher.go#L101-L166
4,526
ligato/cn-infra
datasync/syncbase/watcher.go
PropagateResync
func (adapter *Registry) PropagateResync(ctx context.Context, txData map[string]datasync.ChangeValue) error { var events []func(done chan error) adapter.lastRev.Cleanup() for _, sub := range adapter.subscriptions { items := map[string]datasync.KeyValIterator{} for _, prefix := range sub.KeyPrefixes { var kvs []datasync.KeyVal for key, val := range txData { if strings.HasPrefix(key, prefix) { // TODO: call Put only once for each key (different subscriptions) adapter.lastRev.PutWithRevision(key, val) kvs = append(kvs, &KeyVal{ key: key, LazyValue: val, rev: val.GetRevision(), }) } } items[prefix] = NewKVIterator(kvs) } sendTo := func(sub *Subscription) func(done chan error) { return func(done chan error) { sub.ResyncChan <- &ResyncEventDB{ ctx: ctx, its: items, DoneChannel: NewDoneChannel(done), } } } events = append(events, sendTo(sub)) } done := make(chan error, 1) go AggregateDone(events, done) select { case err := <-done: if err != nil { return err } // TODO: maybe higher timeout for resync event? case <-time.After(PropagateChangesTimeout): logrus.DefaultLogger().Warnf("Timeout of aggregated resync callbacks (%v)", PropagateChangesTimeout) } return nil }
go
func (adapter *Registry) PropagateResync(ctx context.Context, txData map[string]datasync.ChangeValue) error { var events []func(done chan error) adapter.lastRev.Cleanup() for _, sub := range adapter.subscriptions { items := map[string]datasync.KeyValIterator{} for _, prefix := range sub.KeyPrefixes { var kvs []datasync.KeyVal for key, val := range txData { if strings.HasPrefix(key, prefix) { // TODO: call Put only once for each key (different subscriptions) adapter.lastRev.PutWithRevision(key, val) kvs = append(kvs, &KeyVal{ key: key, LazyValue: val, rev: val.GetRevision(), }) } } items[prefix] = NewKVIterator(kvs) } sendTo := func(sub *Subscription) func(done chan error) { return func(done chan error) { sub.ResyncChan <- &ResyncEventDB{ ctx: ctx, its: items, DoneChannel: NewDoneChannel(done), } } } events = append(events, sendTo(sub)) } done := make(chan error, 1) go AggregateDone(events, done) select { case err := <-done: if err != nil { return err } // TODO: maybe higher timeout for resync event? case <-time.After(PropagateChangesTimeout): logrus.DefaultLogger().Warnf("Timeout of aggregated resync callbacks (%v)", PropagateChangesTimeout) } return nil }
[ "func", "(", "adapter", "*", "Registry", ")", "PropagateResync", "(", "ctx", "context", ".", "Context", ",", "txData", "map", "[", "string", "]", "datasync", ".", "ChangeValue", ")", "error", "{", "var", "events", "[", "]", "func", "(", "done", "chan", ...
// PropagateResync fills registered channels with the data.
[ "PropagateResync", "fills", "registered", "channels", "with", "the", "data", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/watcher.go#L169-L222
4,527
ligato/cn-infra
datasync/syncbase/watcher.go
Close
func (reg *WatchDataReg) Close() error { reg.adapter.access.Lock() defer reg.adapter.access.Unlock() for _, sub := range reg.adapter.subscriptions { // subscription should have also change channel, otherwise it is not registered // for change events if sub.ChangeChan != nil && sub.CloseChan != nil { // close the channel with all goroutines under subscription safeclose.Close(sub.CloseChan) } } delete(reg.adapter.subscriptions, reg.ResyncName) return nil }
go
func (reg *WatchDataReg) Close() error { reg.adapter.access.Lock() defer reg.adapter.access.Unlock() for _, sub := range reg.adapter.subscriptions { // subscription should have also change channel, otherwise it is not registered // for change events if sub.ChangeChan != nil && sub.CloseChan != nil { // close the channel with all goroutines under subscription safeclose.Close(sub.CloseChan) } } delete(reg.adapter.subscriptions, reg.ResyncName) return nil }
[ "func", "(", "reg", "*", "WatchDataReg", ")", "Close", "(", ")", "error", "{", "reg", ".", "adapter", ".", "access", ".", "Lock", "(", ")", "\n", "defer", "reg", ".", "adapter", ".", "access", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "su...
// Close stops watching of particular KeyPrefixes.
[ "Close", "stops", "watching", "of", "particular", "KeyPrefixes", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/watcher.go#L225-L241
4,528
ligato/cn-infra
datasync/syncbase/watcher.go
Register
func (reg *WatchDataReg) Register(resyncName, keyPrefix string) error { reg.adapter.access.Lock() defer reg.adapter.access.Unlock() for resName, sub := range reg.adapter.subscriptions { if resName == resyncName { // Verify that prefix does not exist yet for _, regPrefix := range sub.KeyPrefixes { if regPrefix == keyPrefix { return fmt.Errorf("prefix %q already exists", keyPrefix) } } sub.KeyPrefixes = append(sub.KeyPrefixes, keyPrefix) return nil } } return fmt.Errorf("cannot register prefix %s, resync name %s not found", keyPrefix, resyncName) }
go
func (reg *WatchDataReg) Register(resyncName, keyPrefix string) error { reg.adapter.access.Lock() defer reg.adapter.access.Unlock() for resName, sub := range reg.adapter.subscriptions { if resName == resyncName { // Verify that prefix does not exist yet for _, regPrefix := range sub.KeyPrefixes { if regPrefix == keyPrefix { return fmt.Errorf("prefix %q already exists", keyPrefix) } } sub.KeyPrefixes = append(sub.KeyPrefixes, keyPrefix) return nil } } return fmt.Errorf("cannot register prefix %s, resync name %s not found", keyPrefix, resyncName) }
[ "func", "(", "reg", "*", "WatchDataReg", ")", "Register", "(", "resyncName", ",", "keyPrefix", "string", ")", "error", "{", "reg", ".", "adapter", ".", "access", ".", "Lock", "(", ")", "\n", "defer", "reg", ".", "adapter", ".", "access", ".", "Unlock",...
// Register starts watching of particular key prefix. Method returns error if key which should be added // already exists
[ "Register", "starts", "watching", "of", "particular", "key", "prefix", ".", "Method", "returns", "error", "if", "key", "which", "should", "be", "added", "already", "exists" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/watcher.go#L245-L262
4,529
ligato/cn-infra
datasync/syncbase/watcher.go
Unregister
func (reg *WatchDataReg) Unregister(keyPrefix string) error { reg.adapter.access.Lock() defer reg.adapter.access.Unlock() subs := reg.adapter.subscriptions[reg.ResyncName] // verify if key is registered for change events if subs.ChangeChan == nil { // not an error logrus.DefaultLogger().Infof("key %v not registered for change events", keyPrefix) return nil } if subs.CloseChan == nil { return fmt.Errorf("unable to unregister key %v, close channel in subscription is nil", keyPrefix) } for index, prefix := range subs.KeyPrefixes { if prefix == keyPrefix { subs.KeyPrefixes = append(subs.KeyPrefixes[:index], subs.KeyPrefixes[index+1:]...) subs.CloseChan <- keyPrefix logrus.DefaultLogger().WithField("resyncName", reg.ResyncName).Infof("Key %v removed from subscription", keyPrefix) return nil } } return fmt.Errorf("key %v to unregister was not found", keyPrefix) }
go
func (reg *WatchDataReg) Unregister(keyPrefix string) error { reg.adapter.access.Lock() defer reg.adapter.access.Unlock() subs := reg.adapter.subscriptions[reg.ResyncName] // verify if key is registered for change events if subs.ChangeChan == nil { // not an error logrus.DefaultLogger().Infof("key %v not registered for change events", keyPrefix) return nil } if subs.CloseChan == nil { return fmt.Errorf("unable to unregister key %v, close channel in subscription is nil", keyPrefix) } for index, prefix := range subs.KeyPrefixes { if prefix == keyPrefix { subs.KeyPrefixes = append(subs.KeyPrefixes[:index], subs.KeyPrefixes[index+1:]...) subs.CloseChan <- keyPrefix logrus.DefaultLogger().WithField("resyncName", reg.ResyncName).Infof("Key %v removed from subscription", keyPrefix) return nil } } return fmt.Errorf("key %v to unregister was not found", keyPrefix) }
[ "func", "(", "reg", "*", "WatchDataReg", ")", "Unregister", "(", "keyPrefix", "string", ")", "error", "{", "reg", ".", "adapter", ".", "access", ".", "Lock", "(", ")", "\n", "defer", "reg", ".", "adapter", ".", "access", ".", "Unlock", "(", ")", "\n\...
// Unregister stops watching of particular key prefix. Method returns error if key which should be removed // does not exist or in case the channel to close goroutine is nil
[ "Unregister", "stops", "watching", "of", "particular", "key", "prefix", ".", "Method", "returns", "error", "if", "key", "which", "should", "be", "removed", "does", "not", "exist", "or", "in", "case", "the", "channel", "to", "close", "goroutine", "is", "nil" ...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/watcher.go#L266-L291
4,530
ligato/cn-infra
agent/options.go
StartTimeout
func StartTimeout(timeout time.Duration) Option { return func(o *Options) { o.StartTimeout = timeout } }
go
func StartTimeout(timeout time.Duration) Option { return func(o *Options) { o.StartTimeout = timeout } }
[ "func", "StartTimeout", "(", "timeout", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "StartTimeout", "=", "timeout", "\n", "}", "\n", "}" ]
// StartTimeout returns an Option that sets timeout for the start of Agent.
[ "StartTimeout", "returns", "an", "Option", "that", "sets", "timeout", "for", "the", "start", "of", "Agent", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/agent/options.go#L73-L77
4,531
ligato/cn-infra
agent/options.go
StopTimeout
func StopTimeout(timeout time.Duration) Option { return func(o *Options) { o.StopTimeout = timeout } }
go
func StopTimeout(timeout time.Duration) Option { return func(o *Options) { o.StopTimeout = timeout } }
[ "func", "StopTimeout", "(", "timeout", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "StopTimeout", "=", "timeout", "\n", "}", "\n", "}" ]
// StopTimeout returns an Option that sets timeout for the stop of Agent.
[ "StopTimeout", "returns", "an", "Option", "that", "sets", "timeout", "for", "the", "stop", "of", "Agent", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/agent/options.go#L80-L84
4,532
ligato/cn-infra
agent/options.go
Version
func Version(buildVer, buildDate, commitHash string) Option { return func(o *Options) { BuildVersion = buildVer BuildDate = buildDate CommitHash = commitHash } }
go
func Version(buildVer, buildDate, commitHash string) Option { return func(o *Options) { BuildVersion = buildVer BuildDate = buildDate CommitHash = commitHash } }
[ "func", "Version", "(", "buildVer", ",", "buildDate", ",", "commitHash", "string", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "BuildVersion", "=", "buildVer", "\n", "BuildDate", "=", "buildDate", "\n", "CommitHash", "=", "com...
// Version returns an Option that sets the version of the Agent to the entered string
[ "Version", "returns", "an", "Option", "that", "sets", "the", "version", "of", "the", "Agent", "to", "the", "entered", "string" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/agent/options.go#L87-L93
4,533
ligato/cn-infra
agent/options.go
QuitSignals
func QuitSignals(sigs ...os.Signal) Option { return func(o *Options) { o.QuitSignals = sigs } }
go
func QuitSignals(sigs ...os.Signal) Option { return func(o *Options) { o.QuitSignals = sigs } }
[ "func", "QuitSignals", "(", "sigs", "...", "os", ".", "Signal", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "QuitSignals", "=", "sigs", "\n", "}", "\n", "}" ]
// QuitSignals returns an Option that will set signals which stop Agent
[ "QuitSignals", "returns", "an", "Option", "that", "will", "set", "signals", "which", "stop", "Agent" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/agent/options.go#L103-L107
4,534
ligato/cn-infra
agent/options.go
Plugins
func Plugins(plugins ...infra.Plugin) Option { return func(o *Options) { o.Plugins = append(o.Plugins, plugins...) } }
go
func Plugins(plugins ...infra.Plugin) Option { return func(o *Options) { o.Plugins = append(o.Plugins, plugins...) } }
[ "func", "Plugins", "(", "plugins", "...", "infra", ".", "Plugin", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "o", ".", "Plugins", "=", "append", "(", "o", ".", "Plugins", ",", "plugins", "...", ")", "\n", "}", "\n", ...
// Plugins creates an Option that adds a list of Plugins to the Agent's Plugin list
[ "Plugins", "creates", "an", "Option", "that", "adds", "a", "list", "of", "Plugins", "to", "the", "Agent", "s", "Plugin", "list" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/agent/options.go#L117-L121
4,535
ligato/cn-infra
agent/options.go
AllPlugins
func AllPlugins(plugins ...infra.Plugin) Option { return func(o *Options) { infraLogger.Debugf("AllPlugins with %d plugins", len(plugins)) for _, plugin := range plugins { typ := reflect.TypeOf(plugin) infraLogger.Debugf("searching for all deps in: %v (type: %v)", plugin, typ) foundPlugins, err := findPlugins(reflect.ValueOf(plugin), o.pluginMap) if err != nil { panic(err) } infraLogger.Debugf("found %d plugins in: %v (type: %v)", len(foundPlugins), plugin, typ) for _, plug := range foundPlugins { infraLogger.Debugf(" - plugin: %v (%v)", plug, reflect.TypeOf(plug)) if _, ok := o.pluginNames[plug.String()]; ok { infraLogger.Fatalf("plugin with name %q already registered", plug.String()) } o.pluginNames[plug.String()] = struct{}{} } o.Plugins = append(o.Plugins, foundPlugins...) // TODO: perhaps set plugin name to typ.String() if it's empty /*p, ok := plugin.(core.PluginNamed) if !ok { p = core.NamePlugin(typ.String(), plugin) }*/ if _, ok := o.pluginNames[plugin.String()]; ok { infraLogger.Fatalf("plugin with name %q already registered, custom name should be used", plugin.String()) } o.pluginNames[plugin.String()] = struct{}{} o.Plugins = append(o.Plugins, plugin) } } }
go
func AllPlugins(plugins ...infra.Plugin) Option { return func(o *Options) { infraLogger.Debugf("AllPlugins with %d plugins", len(plugins)) for _, plugin := range plugins { typ := reflect.TypeOf(plugin) infraLogger.Debugf("searching for all deps in: %v (type: %v)", plugin, typ) foundPlugins, err := findPlugins(reflect.ValueOf(plugin), o.pluginMap) if err != nil { panic(err) } infraLogger.Debugf("found %d plugins in: %v (type: %v)", len(foundPlugins), plugin, typ) for _, plug := range foundPlugins { infraLogger.Debugf(" - plugin: %v (%v)", plug, reflect.TypeOf(plug)) if _, ok := o.pluginNames[plug.String()]; ok { infraLogger.Fatalf("plugin with name %q already registered", plug.String()) } o.pluginNames[plug.String()] = struct{}{} } o.Plugins = append(o.Plugins, foundPlugins...) // TODO: perhaps set plugin name to typ.String() if it's empty /*p, ok := plugin.(core.PluginNamed) if !ok { p = core.NamePlugin(typ.String(), plugin) }*/ if _, ok := o.pluginNames[plugin.String()]; ok { infraLogger.Fatalf("plugin with name %q already registered, custom name should be used", plugin.String()) } o.pluginNames[plugin.String()] = struct{}{} o.Plugins = append(o.Plugins, plugin) } } }
[ "func", "AllPlugins", "(", "plugins", "...", "infra", ".", "Plugin", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "{", "infraLogger", ".", "Debugf", "(", "\"", "\"", ",", "len", "(", "plugins", ")", ")", "\n\n", "for", "_", ...
// AllPlugins creates an Option that adds all of the nested // plugins recursively to the Agent's plugin list.
[ "AllPlugins", "creates", "an", "Option", "that", "adds", "all", "of", "the", "nested", "plugins", "recursively", "to", "the", "Agent", "s", "plugin", "list", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/agent/options.go#L125-L162
4,536
ligato/cn-infra
db/keyval/redis/bytes_txn_impl.go
Put
func (tx *Txn) Put(key string, value []byte) keyval.BytesTxn { if tx.addPrefix != nil { key = tx.addPrefix(key) } tx.ops = append(tx.ops, op{key, value, false}) return tx }
go
func (tx *Txn) Put(key string, value []byte) keyval.BytesTxn { if tx.addPrefix != nil { key = tx.addPrefix(key) } tx.ops = append(tx.ops, op{key, value, false}) return tx }
[ "func", "(", "tx", "*", "Txn", ")", "Put", "(", "key", "string", ",", "value", "[", "]", "byte", ")", "keyval", ".", "BytesTxn", "{", "if", "tx", ".", "addPrefix", "!=", "nil", "{", "key", "=", "tx", ".", "addPrefix", "(", "key", ")", "\n", "}"...
// Put adds a new 'put' operation to a previously created transaction. // If the key does not exist in the data store, a new key-value item // will be added to the data store. If the key exists in the data store, // the existing value will be overwritten with the value from this // operation.
[ "Put", "adds", "a", "new", "put", "operation", "to", "a", "previously", "created", "transaction", ".", "If", "the", "key", "does", "not", "exist", "in", "the", "data", "store", "a", "new", "key", "-", "value", "item", "will", "be", "added", "to", "the"...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/redis/bytes_txn_impl.go#L46-L52
4,537
ligato/cn-infra
datasync/kvdbsync/iterator.go
GetNext
func (it *Iterator) GetNext() (kv datasync.KeyVal, stop bool) { kv, stop = it.delegate.GetNext() if stop { return nil, stop } return kv, stop }
go
func (it *Iterator) GetNext() (kv datasync.KeyVal, stop bool) { kv, stop = it.delegate.GetNext() if stop { return nil, stop } return kv, stop }
[ "func", "(", "it", "*", "Iterator", ")", "GetNext", "(", ")", "(", "kv", "datasync", ".", "KeyVal", ",", "stop", "bool", ")", "{", "kv", ",", "stop", "=", "it", ".", "delegate", ".", "GetNext", "(", ")", "\n", "if", "stop", "{", "return", "nil", ...
// GetNext only delegates the call to internal iterator.
[ "GetNext", "only", "delegates", "the", "call", "to", "internal", "iterator", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/kvdbsync/iterator.go#L33-L39
4,538
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
Init
func (p *Plugin) Init() error { // write initial status data into ETCD p.agentStat = &status.AgentStatus{ State: status.OperationalState_INIT, BuildVersion: agent.BuildVersion, BuildDate: agent.BuildDate, CommitHash: agent.CommitHash, StartTime: time.Now().Unix(), LastChange: time.Now().Unix(), } // initial empty interface status p.interfaceStat = &status.InterfaceStats{} // init pluginStat map p.pluginStat = make(map[string]*status.PluginStatus) // init map with plugin state probes p.pluginProbe = make(map[string]PluginStateProbe) // prepare context for all go routines p.ctx, p.cancel = context.WithCancel(context.Background()) return nil }
go
func (p *Plugin) Init() error { // write initial status data into ETCD p.agentStat = &status.AgentStatus{ State: status.OperationalState_INIT, BuildVersion: agent.BuildVersion, BuildDate: agent.BuildDate, CommitHash: agent.CommitHash, StartTime: time.Now().Unix(), LastChange: time.Now().Unix(), } // initial empty interface status p.interfaceStat = &status.InterfaceStats{} // init pluginStat map p.pluginStat = make(map[string]*status.PluginStatus) // init map with plugin state probes p.pluginProbe = make(map[string]PluginStateProbe) // prepare context for all go routines p.ctx, p.cancel = context.WithCancel(context.Background()) return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Init", "(", ")", "error", "{", "// write initial status data into ETCD", "p", ".", "agentStat", "=", "&", "status", ".", "AgentStatus", "{", "State", ":", "status", ".", "OperationalState_INIT", ",", "BuildVersion", ":", ...
// Init prepares the initial status data.
[ "Init", "prepares", "the", "initial", "status", "data", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L61-L85
4,539
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
AfterInit
func (p *Plugin) AfterInit() error { p.access.Lock() defer p.access.Unlock() // do periodic status probing for plugins that have provided the probe function go p.periodicProbing(p.ctx) // do periodic updates of the state data in ETCD go p.periodicUpdates(p.ctx) p.publishAgentData() // transition to OK state if there are no plugins if len(p.pluginStat) == 0 { p.agentStat.State = status.OperationalState_OK p.agentStat.LastChange = time.Now().Unix() p.publishAgentData() } return nil }
go
func (p *Plugin) AfterInit() error { p.access.Lock() defer p.access.Unlock() // do periodic status probing for plugins that have provided the probe function go p.periodicProbing(p.ctx) // do periodic updates of the state data in ETCD go p.periodicUpdates(p.ctx) p.publishAgentData() // transition to OK state if there are no plugins if len(p.pluginStat) == 0 { p.agentStat.State = status.OperationalState_OK p.agentStat.LastChange = time.Now().Unix() p.publishAgentData() } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "AfterInit", "(", ")", "error", "{", "p", ".", "access", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "access", ".", "Unlock", "(", ")", "\n\n", "// do periodic status probing for plugins that have provided the probe fu...
// AfterInit starts go routines for periodic probing and periodic updates. // Initial state data are published via the injected transport.
[ "AfterInit", "starts", "go", "routines", "for", "periodic", "probing", "and", "periodic", "updates", ".", "Initial", "state", "data", "are", "published", "via", "the", "injected", "transport", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L89-L109
4,540
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
Close
func (p *Plugin) Close() error { p.cancel() p.wg.Wait() return nil }
go
func (p *Plugin) Close() error { p.cancel() p.wg.Wait() return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Close", "(", ")", "error", "{", "p", ".", "cancel", "(", ")", "\n", "p", ".", "wg", ".", "Wait", "(", ")", "\n\n", "return", "nil", "\n", "}" ]
// Close stops go routines for periodic probing and periodic updates.
[ "Close", "stops", "go", "routines", "for", "periodic", "probing", "and", "periodic", "updates", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L112-L117
4,541
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
Register
func (p *Plugin) Register(pluginName infra.PluginName, probe PluginStateProbe) { p.access.Lock() defer p.access.Unlock() stat := &status.PluginStatus{ State: status.OperationalState_INIT, LastChange: time.Now().Unix(), } p.pluginStat[string(pluginName)] = stat if probe != nil { p.pluginProbe[string(pluginName)] = probe } // write initial status data into ETCD p.publishPluginData(pluginName, stat) p.Log.Debugf("Plugin %v: status check probe registered", pluginName) }
go
func (p *Plugin) Register(pluginName infra.PluginName, probe PluginStateProbe) { p.access.Lock() defer p.access.Unlock() stat := &status.PluginStatus{ State: status.OperationalState_INIT, LastChange: time.Now().Unix(), } p.pluginStat[string(pluginName)] = stat if probe != nil { p.pluginProbe[string(pluginName)] = probe } // write initial status data into ETCD p.publishPluginData(pluginName, stat) p.Log.Debugf("Plugin %v: status check probe registered", pluginName) }
[ "func", "(", "p", "*", "Plugin", ")", "Register", "(", "pluginName", "infra", ".", "PluginName", ",", "probe", "PluginStateProbe", ")", "{", "p", ".", "access", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "access", ".", "Unlock", "(", ")", "\n\n"...
// Register a plugin for status change reporting.
[ "Register", "a", "plugin", "for", "status", "change", "reporting", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L120-L138
4,542
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
ReportStateChange
func (p *Plugin) ReportStateChange(pluginName infra.PluginName, state PluginState, lastError error) { p.reportStateChange(pluginName, state, lastError) }
go
func (p *Plugin) ReportStateChange(pluginName infra.PluginName, state PluginState, lastError error) { p.reportStateChange(pluginName, state, lastError) }
[ "func", "(", "p", "*", "Plugin", ")", "ReportStateChange", "(", "pluginName", "infra", ".", "PluginName", ",", "state", "PluginState", ",", "lastError", "error", ")", "{", "p", ".", "reportStateChange", "(", "pluginName", ",", "state", ",", "lastError", ")",...
// ReportStateChange can be used to report a change in the status of a previously registered plugin.
[ "ReportStateChange", "can", "be", "used", "to", "report", "a", "change", "in", "the", "status", "of", "a", "previously", "registered", "plugin", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L141-L143
4,543
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
ReportStateChangeWithMeta
func (p *Plugin) ReportStateChangeWithMeta(pluginName infra.PluginName, state PluginState, lastError error, meta proto.Message) { p.reportStateChange(pluginName, state, lastError) switch data := meta.(type) { case *status.InterfaceStats_Interface: p.reportInterfaceStateChange(data) default: p.Log.Debug("Unknown type of status metadata") } }
go
func (p *Plugin) ReportStateChangeWithMeta(pluginName infra.PluginName, state PluginState, lastError error, meta proto.Message) { p.reportStateChange(pluginName, state, lastError) switch data := meta.(type) { case *status.InterfaceStats_Interface: p.reportInterfaceStateChange(data) default: p.Log.Debug("Unknown type of status metadata") } }
[ "func", "(", "p", "*", "Plugin", ")", "ReportStateChangeWithMeta", "(", "pluginName", "infra", ".", "PluginName", ",", "state", "PluginState", ",", "lastError", "error", ",", "meta", "proto", ".", "Message", ")", "{", "p", ".", "reportStateChange", "(", "plu...
// ReportStateChangeWithMeta can be used to report a change in the status of a previously registered plugin and report // the specific metadata state
[ "ReportStateChangeWithMeta", "can", "be", "used", "to", "report", "a", "change", "in", "the", "status", "of", "a", "previously", "registered", "plugin", "and", "report", "the", "specific", "metadata", "state" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L147-L156
4,544
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
publishAgentData
func (p *Plugin) publishAgentData() error { p.agentStat.LastUpdate = time.Now().Unix() if p.Transport != nil { return p.Transport.Put(status.AgentStatusKey(), p.agentStat) } return nil }
go
func (p *Plugin) publishAgentData() error { p.agentStat.LastUpdate = time.Now().Unix() if p.Transport != nil { return p.Transport.Put(status.AgentStatusKey(), p.agentStat) } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "publishAgentData", "(", ")", "error", "{", "p", ".", "agentStat", ".", "LastUpdate", "=", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "\n", "if", "p", ".", "Transport", "!=", "nil", "{", "return", "...
// publishAgentData writes the current global agent state into ETCD.
[ "publishAgentData", "writes", "the", "current", "global", "agent", "state", "into", "ETCD", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L256-L262
4,545
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
publishPluginData
func (p *Plugin) publishPluginData(pluginName infra.PluginName, pluginStat *status.PluginStatus) error { pluginStat.LastUpdate = time.Now().Unix() if p.Transport != nil { return p.Transport.Put(status.PluginStatusKey(string(pluginName)), pluginStat) } return nil }
go
func (p *Plugin) publishPluginData(pluginName infra.PluginName, pluginStat *status.PluginStatus) error { pluginStat.LastUpdate = time.Now().Unix() if p.Transport != nil { return p.Transport.Put(status.PluginStatusKey(string(pluginName)), pluginStat) } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "publishPluginData", "(", "pluginName", "infra", ".", "PluginName", ",", "pluginStat", "*", "status", ".", "PluginStatus", ")", "error", "{", "pluginStat", ".", "LastUpdate", "=", "time", ".", "Now", "(", ")", ".", "...
// publishPluginData writes the current plugin state into ETCD.
[ "publishPluginData", "writes", "the", "current", "plugin", "state", "into", "ETCD", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L265-L271
4,546
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
publishAllData
func (p *Plugin) publishAllData() { p.access.Lock() defer p.access.Unlock() p.publishAgentData() for name, s := range p.pluginStat { p.publishPluginData(infra.PluginName(name), s) } }
go
func (p *Plugin) publishAllData() { p.access.Lock() defer p.access.Unlock() p.publishAgentData() for name, s := range p.pluginStat { p.publishPluginData(infra.PluginName(name), s) } }
[ "func", "(", "p", "*", "Plugin", ")", "publishAllData", "(", ")", "{", "p", ".", "access", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "access", ".", "Unlock", "(", ")", "\n\n", "p", ".", "publishAgentData", "(", ")", "\n", "for", "name", ","...
// publishAllData publishes global agent + all plugins state data into ETCD.
[ "publishAllData", "publishes", "global", "agent", "+", "all", "plugins", "state", "data", "into", "ETCD", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L274-L282
4,547
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
periodicProbing
func (p *Plugin) periodicProbing(ctx context.Context) { p.wg.Add(1) defer p.wg.Done() for { select { case <-time.After(PeriodicProbingTimeout): for pluginName, probe := range p.pluginProbe { state, lastErr := probe() p.ReportStateChange(infra.PluginName(pluginName), state, lastErr) // just check in-between probes if the plugin is closing select { case <-ctx.Done(): return default: continue } } case <-ctx.Done(): return } } }
go
func (p *Plugin) periodicProbing(ctx context.Context) { p.wg.Add(1) defer p.wg.Done() for { select { case <-time.After(PeriodicProbingTimeout): for pluginName, probe := range p.pluginProbe { state, lastErr := probe() p.ReportStateChange(infra.PluginName(pluginName), state, lastErr) // just check in-between probes if the plugin is closing select { case <-ctx.Done(): return default: continue } } case <-ctx.Done(): return } } }
[ "func", "(", "p", "*", "Plugin", ")", "periodicProbing", "(", "ctx", "context", ".", "Context", ")", "{", "p", ".", "wg", ".", "Add", "(", "1", ")", "\n", "defer", "p", ".", "wg", ".", "Done", "(", ")", "\n\n", "for", "{", "select", "{", "case"...
// periodicProbing does periodic status probing for all plugins // that have registered probe functions.
[ "periodicProbing", "does", "periodic", "status", "probing", "for", "all", "plugins", "that", "have", "registered", "probe", "functions", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L286-L309
4,548
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
periodicUpdates
func (p *Plugin) periodicUpdates(ctx context.Context) { p.wg.Add(1) defer p.wg.Done() for { select { case <-time.After(PeriodicWriteTimeout): p.publishAllData() case <-ctx.Done(): return } } }
go
func (p *Plugin) periodicUpdates(ctx context.Context) { p.wg.Add(1) defer p.wg.Done() for { select { case <-time.After(PeriodicWriteTimeout): p.publishAllData() case <-ctx.Done(): return } } }
[ "func", "(", "p", "*", "Plugin", ")", "periodicUpdates", "(", "ctx", "context", ".", "Context", ")", "{", "p", ".", "wg", ".", "Add", "(", "1", ")", "\n", "defer", "p", ".", "wg", ".", "Done", "(", ")", "\n\n", "for", "{", "select", "{", "case"...
// periodicUpdates does periodic writes of state data into ETCD.
[ "periodicUpdates", "does", "periodic", "writes", "of", "state", "data", "into", "ETCD", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L312-L325
4,549
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
getAgentState
func (p *Plugin) getAgentState() status.OperationalState { p.access.Lock() defer p.access.Unlock() return p.agentStat.State }
go
func (p *Plugin) getAgentState() status.OperationalState { p.access.Lock() defer p.access.Unlock() return p.agentStat.State }
[ "func", "(", "p", "*", "Plugin", ")", "getAgentState", "(", ")", "status", ".", "OperationalState", "{", "p", ".", "access", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "access", ".", "Unlock", "(", ")", "\n", "return", "p", ".", "agentStat", "...
// getAgentState return current global operational state of the agent.
[ "getAgentState", "return", "current", "global", "operational", "state", "of", "the", "agent", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L328-L332
4,550
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
GetAllPluginStatus
func (p *Plugin) GetAllPluginStatus() map[string]*status.PluginStatus { //TODO - used currently, will be removed after incoporating improvements for exposing copy of map p.access.Lock() defer p.access.Unlock() return p.pluginStat }
go
func (p *Plugin) GetAllPluginStatus() map[string]*status.PluginStatus { //TODO - used currently, will be removed after incoporating improvements for exposing copy of map p.access.Lock() defer p.access.Unlock() return p.pluginStat }
[ "func", "(", "p", "*", "Plugin", ")", "GetAllPluginStatus", "(", ")", "map", "[", "string", "]", "*", "status", ".", "PluginStatus", "{", "//TODO - used currently, will be removed after incoporating improvements for exposing copy of map", "p", ".", "access", ".", "Lock"...
// GetAllPluginStatus returns a map containing pluginname and its status, for all plugins
[ "GetAllPluginStatus", "returns", "a", "map", "containing", "pluginname", "and", "its", "status", "for", "all", "plugins" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L335-L341
4,551
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
GetInterfaceStats
func (p *Plugin) GetInterfaceStats() status.InterfaceStats { p.access.Lock() defer p.access.Unlock() return *p.interfaceStat }
go
func (p *Plugin) GetInterfaceStats() status.InterfaceStats { p.access.Lock() defer p.access.Unlock() return *p.interfaceStat }
[ "func", "(", "p", "*", "Plugin", ")", "GetInterfaceStats", "(", ")", "status", ".", "InterfaceStats", "{", "p", ".", "access", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "access", ".", "Unlock", "(", ")", "\n\n", "return", "*", "p", ".", "inte...
// GetInterfaceStats returns current global operational status of interfaces
[ "GetInterfaceStats", "returns", "current", "global", "operational", "status", "of", "interfaces" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L344-L349
4,552
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
GetAgentStatus
func (p *Plugin) GetAgentStatus() status.AgentStatus { p.access.Lock() defer p.access.Unlock() return *p.agentStat }
go
func (p *Plugin) GetAgentStatus() status.AgentStatus { p.access.Lock() defer p.access.Unlock() return *p.agentStat }
[ "func", "(", "p", "*", "Plugin", ")", "GetAgentStatus", "(", ")", "status", ".", "AgentStatus", "{", "p", ".", "access", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "access", ".", "Unlock", "(", ")", "\n", "return", "*", "p", ".", "agentStat", ...
// GetAgentStatus return current global operational state of the agent.
[ "GetAgentStatus", "return", "current", "global", "operational", "state", "of", "the", "agent", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L352-L356
4,553
ligato/cn-infra
health/statuscheck/plugin_impl_statuscheck.go
stateToProto
func stateToProto(state PluginState) status.OperationalState { switch state { case Init: return status.OperationalState_INIT case OK: return status.OperationalState_OK default: return status.OperationalState_ERROR } }
go
func stateToProto(state PluginState) status.OperationalState { switch state { case Init: return status.OperationalState_INIT case OK: return status.OperationalState_OK default: return status.OperationalState_ERROR } }
[ "func", "stateToProto", "(", "state", "PluginState", ")", "status", ".", "OperationalState", "{", "switch", "state", "{", "case", "Init", ":", "return", "status", ".", "OperationalState_INIT", "\n", "case", "OK", ":", "return", "status", ".", "OperationalState_O...
// stateToProto converts agent state type into protobuf agent state type.
[ "stateToProto", "converts", "agent", "state", "type", "into", "protobuf", "agent", "state", "type", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/plugin_impl_statuscheck.go#L359-L368
4,554
ligato/cn-infra
examples/process-manager-plugin/basic-scenario/main.go
runWatcher
func (p *PMExample) runWatcher(state *status.ProcessStatus, notifyChan chan status.ProcessStatus) { for { select { case currentState, ok := <-notifyChan: if !ok { p.Log.Infof("===>(watcher) process watcher ended") return } *state = currentState p.Log.Infof("===>(watcher) received test process state: %s", currentState) } } }
go
func (p *PMExample) runWatcher(state *status.ProcessStatus, notifyChan chan status.ProcessStatus) { for { select { case currentState, ok := <-notifyChan: if !ok { p.Log.Infof("===>(watcher) process watcher ended") return } *state = currentState p.Log.Infof("===>(watcher) received test process state: %s", currentState) } } }
[ "func", "(", "p", "*", "PMExample", ")", "runWatcher", "(", "state", "*", "status", ".", "ProcessStatus", ",", "notifyChan", "chan", "status", ".", "ProcessStatus", ")", "{", "for", "{", "select", "{", "case", "currentState", ",", "ok", ":=", "<-", "noti...
// Starts the process watcher using provided chanel.
[ "Starts", "the", "process", "watcher", "using", "provided", "chanel", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/process-manager-plugin/basic-scenario/main.go#L185-L197
4,555
ligato/cn-infra
messaging/kafka/client/consumer.go
NewConsumer
func NewConsumer(config *Config, wg *sync.WaitGroup) (*Consumer, error) { if config.Debug { config.Logger.SetLevel(logging.DebugLevel) } config.Logger.Debug("entering NewConsumer ...") if err := config.ValidateConsumerConfig(); err != nil { return nil, err } config.Logger.Debugf("Consumer config: %#v", config) // set consumer config params config.ConsumerConfig().Group.Return.Notifications = config.RecvNotification config.ProducerConfig().Consumer.Return.Errors = config.RecvError config.ConsumerConfig().Consumer.Offsets.Initial = config.InitialOffset cClient, err := cluster.NewClient(config.Brokers, config.Config) if err != nil { return nil, err } config.Logger.Debug("new client created successfully ...") consumer, err := cluster.NewConsumerFromClient(cClient, config.GroupID, config.Topics) if err != nil { return nil, err } sConsumer, err := sarama.NewConsumerFromClient(cClient) if err != nil { return nil, err } csmr := &Consumer{ Logger: config.Logger, Config: config, SConsumer: sConsumer, Consumer: consumer, closed: false, closeChannel: make(chan struct{}), } // if there is a "waitgroup" arg then use it if wg != nil { csmr.xwg = wg csmr.xwg.Add(1) } return csmr, nil }
go
func NewConsumer(config *Config, wg *sync.WaitGroup) (*Consumer, error) { if config.Debug { config.Logger.SetLevel(logging.DebugLevel) } config.Logger.Debug("entering NewConsumer ...") if err := config.ValidateConsumerConfig(); err != nil { return nil, err } config.Logger.Debugf("Consumer config: %#v", config) // set consumer config params config.ConsumerConfig().Group.Return.Notifications = config.RecvNotification config.ProducerConfig().Consumer.Return.Errors = config.RecvError config.ConsumerConfig().Consumer.Offsets.Initial = config.InitialOffset cClient, err := cluster.NewClient(config.Brokers, config.Config) if err != nil { return nil, err } config.Logger.Debug("new client created successfully ...") consumer, err := cluster.NewConsumerFromClient(cClient, config.GroupID, config.Topics) if err != nil { return nil, err } sConsumer, err := sarama.NewConsumerFromClient(cClient) if err != nil { return nil, err } csmr := &Consumer{ Logger: config.Logger, Config: config, SConsumer: sConsumer, Consumer: consumer, closed: false, closeChannel: make(chan struct{}), } // if there is a "waitgroup" arg then use it if wg != nil { csmr.xwg = wg csmr.xwg.Add(1) } return csmr, nil }
[ "func", "NewConsumer", "(", "config", "*", "Config", ",", "wg", "*", "sync", ".", "WaitGroup", ")", "(", "*", "Consumer", ",", "error", ")", "{", "if", "config", ".", "Debug", "{", "config", ".", "Logger", ".", "SetLevel", "(", "logging", ".", "Debug...
// NewConsumer returns a Consumer instance. If startHandlers is set to true, reading of messages, errors // and notifications is started using new consumer. Otherwise, only instance is returned
[ "NewConsumer", "returns", "a", "Consumer", "instance", ".", "If", "startHandlers", "is", "set", "to", "true", "reading", "of", "messages", "errors", "and", "notifications", "is", "started", "using", "new", "consumer", ".", "Otherwise", "only", "instance", "is", ...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/consumer.go#L55-L103
4,556
ligato/cn-infra
messaging/kafka/client/consumer.go
StartConsumerManualHandlers
func (ref *Consumer) StartConsumerManualHandlers(partitionConsumer sarama.PartitionConsumer) { config := ref.Config config.Logger.Info("Starting message handlers for new manual consumer ...") // if required, start reading from the errors channel if config.ProducerConfig().Consumer.Return.Errors { go ref.manualErrorHandler(partitionConsumer.Errors()) } // start the message handler go ref.messageHandler(partitionConsumer.Messages()) }
go
func (ref *Consumer) StartConsumerManualHandlers(partitionConsumer sarama.PartitionConsumer) { config := ref.Config config.Logger.Info("Starting message handlers for new manual consumer ...") // if required, start reading from the errors channel if config.ProducerConfig().Consumer.Return.Errors { go ref.manualErrorHandler(partitionConsumer.Errors()) } // start the message handler go ref.messageHandler(partitionConsumer.Messages()) }
[ "func", "(", "ref", "*", "Consumer", ")", "StartConsumerManualHandlers", "(", "partitionConsumer", "sarama", ".", "PartitionConsumer", ")", "{", "config", ":=", "ref", ".", "Config", "\n", "config", ".", "Logger", ".", "Info", "(", "\"", "\"", ")", "\n\n", ...
// StartConsumerManualHandlers starts required handlers using sarama partition consumer. Used when partitioner set in config is // manual
[ "StartConsumerManualHandlers", "starts", "required", "handlers", "using", "sarama", "partition", "consumer", ".", "Used", "when", "partitioner", "set", "in", "config", "is", "manual" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/consumer.go#L126-L137
4,557
ligato/cn-infra
messaging/kafka/client/consumer.go
NewClient
func NewClient(config *Config, partitioner string) (sarama.Client, error) { config.Logger.Debug("Creating new consumer") if err := config.ValidateAsyncProducerConfig(); err != nil { return nil, err } config.SetSendSuccess(true) config.SetSuccessChan(make(chan *ProducerMessage)) config.SetSendError(true) config.SetErrorChan(make(chan *ProducerError)) // Required acks will be set in sync/async producer config.RequiredAcks = AcksUnset // set other Producer config params config.ProducerConfig().Producer.Return.Successes = config.SendSuccess config.ProducerConfig().Producer.Return.Errors = config.SendError // set partitioner switch partitioner { case Hash: config.ProducerConfig().Producer.Partitioner = sarama.NewHashPartitioner case Random: config.ProducerConfig().Producer.Partitioner = sarama.NewRandomPartitioner case Manual: config.ProducerConfig().Producer.Partitioner = sarama.NewManualPartitioner default: // Hash partitioner is set as default config.ProducerConfig().Producer.Partitioner = sarama.NewHashPartitioner } config.Logger.Debugf("AsyncProducer config: %#v", config) sClient, err := sarama.NewClient(config.Brokers, &config.Config.Config) if err != nil { fmt.Printf("Error creating consumer client %v", err) return nil, err } return sClient, nil }
go
func NewClient(config *Config, partitioner string) (sarama.Client, error) { config.Logger.Debug("Creating new consumer") if err := config.ValidateAsyncProducerConfig(); err != nil { return nil, err } config.SetSendSuccess(true) config.SetSuccessChan(make(chan *ProducerMessage)) config.SetSendError(true) config.SetErrorChan(make(chan *ProducerError)) // Required acks will be set in sync/async producer config.RequiredAcks = AcksUnset // set other Producer config params config.ProducerConfig().Producer.Return.Successes = config.SendSuccess config.ProducerConfig().Producer.Return.Errors = config.SendError // set partitioner switch partitioner { case Hash: config.ProducerConfig().Producer.Partitioner = sarama.NewHashPartitioner case Random: config.ProducerConfig().Producer.Partitioner = sarama.NewRandomPartitioner case Manual: config.ProducerConfig().Producer.Partitioner = sarama.NewManualPartitioner default: // Hash partitioner is set as default config.ProducerConfig().Producer.Partitioner = sarama.NewHashPartitioner } config.Logger.Debugf("AsyncProducer config: %#v", config) sClient, err := sarama.NewClient(config.Brokers, &config.Config.Config) if err != nil { fmt.Printf("Error creating consumer client %v", err) return nil, err } return sClient, nil }
[ "func", "NewClient", "(", "config", "*", "Config", ",", "partitioner", "string", ")", "(", "sarama", ".", "Client", ",", "error", ")", "{", "config", ".", "Logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "config", ".", "Validate...
// NewClient initializes new sarama client instance from provided config and with defined partitioner
[ "NewClient", "initializes", "new", "sarama", "client", "instance", "from", "provided", "config", "and", "with", "defined", "partitioner" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/consumer.go#L140-L179
4,558
ligato/cn-infra
messaging/kafka/client/consumer.go
Close
func (ref *Consumer) Close() error { ref.Debug("entering consumer close ...") defer func() { ref.Debug("running defer ...") if ref.closed { ref.Debug("consumer already closed ...") ref.Unlock() return } ref.Debug("setting closed ...") ref.closed = true ref.Debug("closing closeChannel channel ...") close(ref.closeChannel) if ref.xwg != nil { ref.xwg.Done() } ref.Unlock() }() ref.Debug("about to lock ...") ref.Lock() ref.Debug("locked ...") if ref.closed { return nil } // close consumer ref.Debug("calling consumer close ....") err := ref.Consumer.Close() if err != nil { ref.Errorf("consumer close error: %v", err) return err } ref.Debug("consumer closed") return nil }
go
func (ref *Consumer) Close() error { ref.Debug("entering consumer close ...") defer func() { ref.Debug("running defer ...") if ref.closed { ref.Debug("consumer already closed ...") ref.Unlock() return } ref.Debug("setting closed ...") ref.closed = true ref.Debug("closing closeChannel channel ...") close(ref.closeChannel) if ref.xwg != nil { ref.xwg.Done() } ref.Unlock() }() ref.Debug("about to lock ...") ref.Lock() ref.Debug("locked ...") if ref.closed { return nil } // close consumer ref.Debug("calling consumer close ....") err := ref.Consumer.Close() if err != nil { ref.Errorf("consumer close error: %v", err) return err } ref.Debug("consumer closed") return nil }
[ "func", "(", "ref", "*", "Consumer", ")", "Close", "(", ")", "error", "{", "ref", ".", "Debug", "(", "\"", "\"", ")", "\n", "defer", "func", "(", ")", "{", "ref", ".", "Debug", "(", "\"", "\"", ")", "\n", "if", "ref", ".", "closed", "{", "ref...
// Close closes the client and consumer
[ "Close", "closes", "the", "client", "and", "consumer" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/consumer.go#L182-L219
4,559
ligato/cn-infra
messaging/kafka/client/consumer.go
PrintNotification
func (ref *Consumer) PrintNotification(note map[string][]int32) { for k, v := range note { fmt.Printf(" Topic: %s\n", k) fmt.Printf(" Partitions: %v\n", v) } }
go
func (ref *Consumer) PrintNotification(note map[string][]int32) { for k, v := range note { fmt.Printf(" Topic: %s\n", k) fmt.Printf(" Partitions: %v\n", v) } }
[ "func", "(", "ref", "*", "Consumer", ")", "PrintNotification", "(", "note", "map", "[", "string", "]", "[", "]", "int32", ")", "{", "for", "k", ",", "v", ":=", "range", "note", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "k", ")", "...
// PrintNotification print the topics and partitions
[ "PrintNotification", "print", "the", "topics", "and", "partitions" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/consumer.go#L267-L272
4,560
ligato/cn-infra
messaging/kafka/client/consumer.go
messageHandler
func (ref *Consumer) messageHandler(in <-chan *sarama.ConsumerMessage) { ref.Debug("messageHandler started ...") var prevValue []byte for { select { case msg := <-in: if msg == nil { continue } consumerMsg := &ConsumerMessage{ Key: msg.Key, Value: msg.Value, PrevValue: prevValue, Topic: msg.Topic, Partition: msg.Partition, Offset: msg.Offset, Timestamp: msg.Timestamp, } // Store value as previous for the next iteration prevValue = consumerMsg.Value select { case ref.Config.RecvMessageChan <- consumerMsg: case <-time.After(1 * time.Second): ref.Warn("Failed to deliver a message") } case <-ref.closeChannel: ref.Debug("Canceling message handler") return } } }
go
func (ref *Consumer) messageHandler(in <-chan *sarama.ConsumerMessage) { ref.Debug("messageHandler started ...") var prevValue []byte for { select { case msg := <-in: if msg == nil { continue } consumerMsg := &ConsumerMessage{ Key: msg.Key, Value: msg.Value, PrevValue: prevValue, Topic: msg.Topic, Partition: msg.Partition, Offset: msg.Offset, Timestamp: msg.Timestamp, } // Store value as previous for the next iteration prevValue = consumerMsg.Value select { case ref.Config.RecvMessageChan <- consumerMsg: case <-time.After(1 * time.Second): ref.Warn("Failed to deliver a message") } case <-ref.closeChannel: ref.Debug("Canceling message handler") return } } }
[ "func", "(", "ref", "*", "Consumer", ")", "messageHandler", "(", "in", "<-", "chan", "*", "sarama", ".", "ConsumerMessage", ")", "{", "ref", ".", "Debug", "(", "\"", "\"", ")", "\n", "var", "prevValue", "[", "]", "byte", "\n\n", "for", "{", "select",...
// messageHandler processes each incoming message
[ "messageHandler", "processes", "each", "incoming", "message" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/consumer.go#L275-L306
4,561
ligato/cn-infra
messaging/kafka/client/consumer.go
manualErrorHandler
func (ref *Consumer) manualErrorHandler(in <-chan *sarama.ConsumerError) { ref.Debug("errorHandler started ...") for { select { case err, more := <-in: if more { ref.Errorf("message error: %T, %v", err, err) ref.Config.RecvErrorChan <- err } case <-ref.closeChannel: ref.Debug("Canceling error handler") return } } }
go
func (ref *Consumer) manualErrorHandler(in <-chan *sarama.ConsumerError) { ref.Debug("errorHandler started ...") for { select { case err, more := <-in: if more { ref.Errorf("message error: %T, %v", err, err) ref.Config.RecvErrorChan <- err } case <-ref.closeChannel: ref.Debug("Canceling error handler") return } } }
[ "func", "(", "ref", "*", "Consumer", ")", "manualErrorHandler", "(", "in", "<-", "chan", "*", "sarama", ".", "ConsumerError", ")", "{", "ref", ".", "Debug", "(", "\"", "\"", ")", "\n", "for", "{", "select", "{", "case", "err", ",", "more", ":=", "<...
// manualErrorHandler processes each error message for partition consumer
[ "manualErrorHandler", "processes", "each", "error", "message", "for", "partition", "consumer" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/consumer.go#L309-L323
4,562
ligato/cn-infra
messaging/kafka/client/consumer.go
errorHandler
func (ref *Consumer) errorHandler(in <-chan error) { ref.Debug("errorHandler started ...") for { select { case err, more := <-in: if more { ref.Errorf("message error: %T, %v", err, err) ref.Config.RecvErrorChan <- err } case <-ref.closeChannel: ref.Debug("Canceling error handler") return } } }
go
func (ref *Consumer) errorHandler(in <-chan error) { ref.Debug("errorHandler started ...") for { select { case err, more := <-in: if more { ref.Errorf("message error: %T, %v", err, err) ref.Config.RecvErrorChan <- err } case <-ref.closeChannel: ref.Debug("Canceling error handler") return } } }
[ "func", "(", "ref", "*", "Consumer", ")", "errorHandler", "(", "in", "<-", "chan", "error", ")", "{", "ref", ".", "Debug", "(", "\"", "\"", ")", "\n", "for", "{", "select", "{", "case", "err", ",", "more", ":=", "<-", "in", ":", "if", "more", "...
// errorHandler processes each error message
[ "errorHandler", "processes", "each", "error", "message" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/consumer.go#L326-L340
4,563
ligato/cn-infra
messaging/kafka/client/consumer.go
notificationHandler
func (ref *Consumer) notificationHandler(in <-chan *cluster.Notification) { ref.Debug("NotificationHandler started ...") for { select { case note := <-in: ref.Config.RecvNotificationChan <- note case <-ref.closeChannel: ref.Debug("Canceling notification handler") return } } }
go
func (ref *Consumer) notificationHandler(in <-chan *cluster.Notification) { ref.Debug("NotificationHandler started ...") for { select { case note := <-in: ref.Config.RecvNotificationChan <- note case <-ref.closeChannel: ref.Debug("Canceling notification handler") return } } }
[ "func", "(", "ref", "*", "Consumer", ")", "notificationHandler", "(", "in", "<-", "chan", "*", "cluster", ".", "Notification", ")", "{", "ref", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "for", "{", "select", "{", "case", "note", ":=", "<-", "in", ...
// NotificationHandler processes each message received when the consumer is rebalanced
[ "NotificationHandler", "processes", "each", "message", "received", "when", "the", "consumer", "is", "rebalanced" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/consumer.go#L343-L355
4,564
ligato/cn-infra
db/keyval/bolt/bolt.go
NewClient
func NewClient(cfg *Config) (client *Client, err error) { db, err := bolt.Open(cfg.DbPath, cfg.FileMode, &bolt.Options{ Timeout: cfg.LockTimeout, }) if err != nil { return nil, err } boltLogger.Infof("bolt path: %v", db.Path()) err = db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists(rootBucket) return err }) if err != nil { return nil, err } c := &Client{ db: db, cfg: *cfg, quit: make(chan struct{}), updateChan: make(chan *updateTx, UpdatesChannelSize), } c.wg.Add(1) go c.startUpdater() return c, nil }
go
func NewClient(cfg *Config) (client *Client, err error) { db, err := bolt.Open(cfg.DbPath, cfg.FileMode, &bolt.Options{ Timeout: cfg.LockTimeout, }) if err != nil { return nil, err } boltLogger.Infof("bolt path: %v", db.Path()) err = db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists(rootBucket) return err }) if err != nil { return nil, err } c := &Client{ db: db, cfg: *cfg, quit: make(chan struct{}), updateChan: make(chan *updateTx, UpdatesChannelSize), } c.wg.Add(1) go c.startUpdater() return c, nil }
[ "func", "NewClient", "(", "cfg", "*", "Config", ")", "(", "client", "*", "Client", ",", "err", "error", ")", "{", "db", ",", "err", ":=", "bolt", ".", "Open", "(", "cfg", ".", "DbPath", ",", "cfg", ".", "FileMode", ",", "&", "bolt", ".", "Options...
// NewClient creates new client for Bolt using given config.
[ "NewClient", "creates", "new", "client", "for", "Bolt", "using", "given", "config", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/bolt/bolt.go#L59-L87
4,565
ligato/cn-infra
db/keyval/bolt/bolt.go
Close
func (c *Client) Close() error { close(c.quit) c.wg.Wait() return c.db.Close() }
go
func (c *Client) Close() error { close(c.quit) c.wg.Wait() return c.db.Close() }
[ "func", "(", "c", "*", "Client", ")", "Close", "(", ")", "error", "{", "close", "(", "c", ".", "quit", ")", "\n", "c", ".", "wg", ".", "Wait", "(", ")", "\n", "return", "c", ".", "db", ".", "Close", "(", ")", "\n", "}" ]
// Close closes Bolt database.
[ "Close", "closes", "Bolt", "database", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/bolt/bolt.go#L90-L94
4,566
ligato/cn-infra
db/keyval/bolt/bolt.go
GetValue
func (c *Client) GetValue(key string) (data []byte, found bool, revision int64, err error) { boltLogger.Debugf("GetValue: %q", key) err = c.db.View(func(tx *bolt.Tx) error { value := tx.Bucket(rootBucket).Get([]byte(key)) if value == nil { return fmt.Errorf("value for key %q not found in bucket", key) } found = true data = append([]byte(nil), value...) // value needs to be copied return nil }) return data, found, 0, err }
go
func (c *Client) GetValue(key string) (data []byte, found bool, revision int64, err error) { boltLogger.Debugf("GetValue: %q", key) err = c.db.View(func(tx *bolt.Tx) error { value := tx.Bucket(rootBucket).Get([]byte(key)) if value == nil { return fmt.Errorf("value for key %q not found in bucket", key) } found = true data = append([]byte(nil), value...) // value needs to be copied return nil }) return data, found, 0, err }
[ "func", "(", "c", "*", "Client", ")", "GetValue", "(", "key", "string", ")", "(", "data", "[", "]", "byte", ",", "found", "bool", ",", "revision", "int64", ",", "err", "error", ")", "{", "boltLogger", ".", "Debugf", "(", "\"", "\"", ",", "key", "...
// GetValue returns data for the given key
[ "GetValue", "returns", "data", "for", "the", "given", "key" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/bolt/bolt.go#L97-L112
4,567
ligato/cn-infra
db/keyval/bolt/bolt.go
Put
func (c *Client) Put(key string, data []byte, opts ...datasync.PutOption) (err error) { boltLogger.Debugf("Put: %q (len=%d)", key, len(data)) prevVal, err := c.safeUpdate(&update{ key: []byte(key), value: data, }) if err != nil { return err } c.bumpWatchers(&watchEvent{ Key: key, Value: data, PrevValue: prevVal, Type: datasync.Put, }) return nil }
go
func (c *Client) Put(key string, data []byte, opts ...datasync.PutOption) (err error) { boltLogger.Debugf("Put: %q (len=%d)", key, len(data)) prevVal, err := c.safeUpdate(&update{ key: []byte(key), value: data, }) if err != nil { return err } c.bumpWatchers(&watchEvent{ Key: key, Value: data, PrevValue: prevVal, Type: datasync.Put, }) return nil }
[ "func", "(", "c", "*", "Client", ")", "Put", "(", "key", "string", ",", "data", "[", "]", "byte", ",", "opts", "...", "datasync", ".", "PutOption", ")", "(", "err", "error", ")", "{", "boltLogger", ".", "Debugf", "(", "\"", "\"", ",", "key", ",",...
// Put stores given data for the key
[ "Put", "stores", "given", "data", "for", "the", "key" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/bolt/bolt.go#L115-L134
4,568
ligato/cn-infra
db/keyval/bolt/bolt.go
Delete
func (c *Client) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) { boltLogger.Debugf("Delete: %q", key) prevVal, err := c.safeUpdate(&update{ key: []byte(key), value: nil, }) if err != nil { return false, err } existed = prevVal != nil c.bumpWatchers(&watchEvent{ Key: key, PrevValue: prevVal, Type: datasync.Delete, }) return existed, err }
go
func (c *Client) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) { boltLogger.Debugf("Delete: %q", key) prevVal, err := c.safeUpdate(&update{ key: []byte(key), value: nil, }) if err != nil { return false, err } existed = prevVal != nil c.bumpWatchers(&watchEvent{ Key: key, PrevValue: prevVal, Type: datasync.Delete, }) return existed, err }
[ "func", "(", "c", "*", "Client", ")", "Delete", "(", "key", "string", ",", "opts", "...", "datasync", ".", "DelOption", ")", "(", "existed", "bool", ",", "err", "error", ")", "{", "boltLogger", ".", "Debugf", "(", "\"", "\"", ",", "key", ")", "\n\n...
// Delete deletes given key
[ "Delete", "deletes", "given", "key" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/bolt/bolt.go#L137-L156
4,569
ligato/cn-infra
db/keyval/bolt/bolt.go
ListKeys
func (c *Client) ListKeys(keyPrefix string) (keyval.BytesKeyIterator, error) { boltLogger.Debugf("ListKeys: %q", keyPrefix) var keys []string err := c.db.View(func(tx *bolt.Tx) error { c := tx.Bucket(rootBucket).Cursor() prefix := []byte(keyPrefix) for k, _ := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, _ = c.Next() { boltLogger.Debugf(" listing key: %q", string(k)) keys = append(keys, string(k)) } return nil }) return &bytesKeyIterator{len: len(keys), keys: keys}, err }
go
func (c *Client) ListKeys(keyPrefix string) (keyval.BytesKeyIterator, error) { boltLogger.Debugf("ListKeys: %q", keyPrefix) var keys []string err := c.db.View(func(tx *bolt.Tx) error { c := tx.Bucket(rootBucket).Cursor() prefix := []byte(keyPrefix) for k, _ := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, _ = c.Next() { boltLogger.Debugf(" listing key: %q", string(k)) keys = append(keys, string(k)) } return nil }) return &bytesKeyIterator{len: len(keys), keys: keys}, err }
[ "func", "(", "c", "*", "Client", ")", "ListKeys", "(", "keyPrefix", "string", ")", "(", "keyval", ".", "BytesKeyIterator", ",", "error", ")", "{", "boltLogger", ".", "Debugf", "(", "\"", "\"", ",", "keyPrefix", ")", "\n\n", "var", "keys", "[", "]", "...
// ListKeys returns iterator with keys for given key prefix
[ "ListKeys", "returns", "iterator", "with", "keys", "for", "given", "key", "prefix" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/bolt/bolt.go#L159-L176
4,570
ligato/cn-infra
db/keyval/bolt/bolt.go
ListValues
func (c *Client) ListValues(keyPrefix string) (keyval.BytesKeyValIterator, error) { boltLogger.Debugf("ListValues: %q", keyPrefix) var pairs []*kvPair err := c.db.View(func(tx *bolt.Tx) error { c := tx.Bucket(rootBucket).Cursor() prefix := []byte(keyPrefix) for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() { boltLogger.Debugf(" listing val: %q (len=%d)", string(k), len(v)) pair := &kvPair{Key: string(k)} pair.Value = append([]byte(nil), v...) // value needs to be copied pairs = append(pairs, pair) } return nil }) return &bytesKeyValIterator{len: len(pairs), pairs: pairs}, err }
go
func (c *Client) ListValues(keyPrefix string) (keyval.BytesKeyValIterator, error) { boltLogger.Debugf("ListValues: %q", keyPrefix) var pairs []*kvPair err := c.db.View(func(tx *bolt.Tx) error { c := tx.Bucket(rootBucket).Cursor() prefix := []byte(keyPrefix) for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() { boltLogger.Debugf(" listing val: %q (len=%d)", string(k), len(v)) pair := &kvPair{Key: string(k)} pair.Value = append([]byte(nil), v...) // value needs to be copied pairs = append(pairs, pair) } return nil }) return &bytesKeyValIterator{len: len(pairs), pairs: pairs}, err }
[ "func", "(", "c", "*", "Client", ")", "ListValues", "(", "keyPrefix", "string", ")", "(", "keyval", ".", "BytesKeyValIterator", ",", "error", ")", "{", "boltLogger", ".", "Debugf", "(", "\"", "\"", ",", "keyPrefix", ")", "\n\n", "var", "pairs", "[", "]...
// ListValues returns iterator with key-value pairs for given key prefix
[ "ListValues", "returns", "iterator", "with", "key", "-", "value", "pairs", "for", "given", "key", "prefix" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/bolt/bolt.go#L179-L200
4,571
ligato/cn-infra
messaging/kafka/client/asyncproducer.go
SendMsgByte
func (ref *AsyncProducer) SendMsgByte(topic string, key []byte, msg []byte, metadata interface{}) { // generate key if none supplied - used by Hash partitioner if key == nil || len(key) == 0 { md5Sum := fmt.Sprintf("%x", md5.Sum(msg)) ref.SendMsgToPartition(topic, ref.Partition, sarama.ByteEncoder([]byte(md5Sum)), sarama.ByteEncoder(msg), metadata) return } ref.SendMsgToPartition(topic, ref.Partition, sarama.ByteEncoder(key), sarama.ByteEncoder(msg), metadata) }
go
func (ref *AsyncProducer) SendMsgByte(topic string, key []byte, msg []byte, metadata interface{}) { // generate key if none supplied - used by Hash partitioner if key == nil || len(key) == 0 { md5Sum := fmt.Sprintf("%x", md5.Sum(msg)) ref.SendMsgToPartition(topic, ref.Partition, sarama.ByteEncoder([]byte(md5Sum)), sarama.ByteEncoder(msg), metadata) return } ref.SendMsgToPartition(topic, ref.Partition, sarama.ByteEncoder(key), sarama.ByteEncoder(msg), metadata) }
[ "func", "(", "ref", "*", "AsyncProducer", ")", "SendMsgByte", "(", "topic", "string", ",", "key", "[", "]", "byte", ",", "msg", "[", "]", "byte", ",", "metadata", "interface", "{", "}", ")", "{", "// generate key if none supplied - used by Hash partitioner", "...
// SendMsgByte sends an async message to Kafka.
[ "SendMsgByte", "sends", "an", "async", "message", "to", "Kafka", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/asyncproducer.go#L115-L123
4,572
ligato/cn-infra
messaging/kafka/client/asyncproducer.go
SendMsgToPartition
func (ref *AsyncProducer) SendMsgToPartition(topic string, partition int32, key Encoder, msg Encoder, metadata interface{}) { if msg == nil { return } message := &sarama.ProducerMessage{ Topic: topic, Partition: partition, Key: key, Value: msg, Metadata: metadata, } ref.Producer.Input() <- message ref.Debugf("message sent: %s", message) return }
go
func (ref *AsyncProducer) SendMsgToPartition(topic string, partition int32, key Encoder, msg Encoder, metadata interface{}) { if msg == nil { return } message := &sarama.ProducerMessage{ Topic: topic, Partition: partition, Key: key, Value: msg, Metadata: metadata, } ref.Producer.Input() <- message ref.Debugf("message sent: %s", message) return }
[ "func", "(", "ref", "*", "AsyncProducer", ")", "SendMsgToPartition", "(", "topic", "string", ",", "partition", "int32", ",", "key", "Encoder", ",", "msg", "Encoder", ",", "metadata", "interface", "{", "}", ")", "{", "if", "msg", "==", "nil", "{", "return...
// SendMsgToPartition sends an async message to Kafka
[ "SendMsgToPartition", "sends", "an", "async", "message", "to", "Kafka" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/asyncproducer.go#L126-L144
4,573
ligato/cn-infra
messaging/kafka/client/asyncproducer.go
successHandler
func (ref *AsyncProducer) successHandler(in <-chan *sarama.ProducerMessage) { ref.Debug("starting success handler ...") for { select { case <-ref.closeChannel: ref.Debug("success handler exited ...") return case msg := <-in: if msg == nil { continue } ref.Debugf("Message is stored in topic(%s)/partition(%d)/offset(%d)\n", msg.Topic, msg.Partition, msg.Offset) pmsg := &ProducerMessage{ Topic: msg.Topic, Key: msg.Key, Value: msg.Value, Metadata: msg.Metadata, Offset: msg.Offset, Partition: msg.Partition, } ref.Config.SuccessChan <- pmsg } } }
go
func (ref *AsyncProducer) successHandler(in <-chan *sarama.ProducerMessage) { ref.Debug("starting success handler ...") for { select { case <-ref.closeChannel: ref.Debug("success handler exited ...") return case msg := <-in: if msg == nil { continue } ref.Debugf("Message is stored in topic(%s)/partition(%d)/offset(%d)\n", msg.Topic, msg.Partition, msg.Offset) pmsg := &ProducerMessage{ Topic: msg.Topic, Key: msg.Key, Value: msg.Value, Metadata: msg.Metadata, Offset: msg.Offset, Partition: msg.Partition, } ref.Config.SuccessChan <- pmsg } } }
[ "func", "(", "ref", "*", "AsyncProducer", ")", "successHandler", "(", "in", "<-", "chan", "*", "sarama", ".", "ProducerMessage", ")", "{", "ref", ".", "Debug", "(", "\"", "\"", ")", "\n", "for", "{", "select", "{", "case", "<-", "ref", ".", "closeCha...
// successHandler handles success messages
[ "successHandler", "handles", "success", "messages" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/asyncproducer.go#L192-L215
4,574
ligato/cn-infra
messaging/kafka/client/asyncproducer.go
errorHandler
func (ref *AsyncProducer) errorHandler(in <-chan *sarama.ProducerError) { ref.Debug("starting error handler ...") for { select { case <-ref.closeChannel: ref.Debug("error handler exited ...") return case perr := <-in: if perr == nil { continue } msg := perr.Msg err := perr.Err pmsg := &ProducerMessage{ Topic: msg.Topic, Key: msg.Key, Value: msg.Value, Metadata: msg.Metadata, Offset: msg.Offset, Partition: msg.Partition, } perr2 := &ProducerError{ ProducerMessage: pmsg, Err: err, } val, _ := msg.Value.Encode() ref.Errorf("message %s errored in topic(%s)/partition(%d)/offset(%d)\n", string(val), pmsg.Topic, pmsg.Partition, pmsg.Offset) ref.Errorf("message error: %v", perr.Err) ref.Config.ErrorChan <- perr2 } } }
go
func (ref *AsyncProducer) errorHandler(in <-chan *sarama.ProducerError) { ref.Debug("starting error handler ...") for { select { case <-ref.closeChannel: ref.Debug("error handler exited ...") return case perr := <-in: if perr == nil { continue } msg := perr.Msg err := perr.Err pmsg := &ProducerMessage{ Topic: msg.Topic, Key: msg.Key, Value: msg.Value, Metadata: msg.Metadata, Offset: msg.Offset, Partition: msg.Partition, } perr2 := &ProducerError{ ProducerMessage: pmsg, Err: err, } val, _ := msg.Value.Encode() ref.Errorf("message %s errored in topic(%s)/partition(%d)/offset(%d)\n", string(val), pmsg.Topic, pmsg.Partition, pmsg.Offset) ref.Errorf("message error: %v", perr.Err) ref.Config.ErrorChan <- perr2 } } }
[ "func", "(", "ref", "*", "AsyncProducer", ")", "errorHandler", "(", "in", "<-", "chan", "*", "sarama", ".", "ProducerError", ")", "{", "ref", ".", "Debug", "(", "\"", "\"", ")", "\n", "for", "{", "select", "{", "case", "<-", "ref", ".", "closeChannel...
// errorHandler handles error messages
[ "errorHandler", "handles", "error", "messages" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/asyncproducer.go#L218-L250
4,575
ligato/cn-infra
config/plugin_config.go
DefineDirFlag
func DefineDirFlag() { if flag.CommandLine.Lookup(DirFlag) == nil { flag.CommandLine.String(DirFlag, DirDefault, DirUsage) } }
go
func DefineDirFlag() { if flag.CommandLine.Lookup(DirFlag) == nil { flag.CommandLine.String(DirFlag, DirDefault, DirUsage) } }
[ "func", "DefineDirFlag", "(", ")", "{", "if", "flag", ".", "CommandLine", ".", "Lookup", "(", "DirFlag", ")", "==", "nil", "{", "flag", ".", "CommandLine", ".", "String", "(", "DirFlag", ",", "DirDefault", ",", "DirUsage", ")", "\n", "}", "\n", "}" ]
// DefineDirFlag defines flag for configuration directory.
[ "DefineDirFlag", "defines", "flag", "for", "configuration", "directory", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/config/plugin_config.go#L55-L59
4,576
ligato/cn-infra
config/plugin_config.go
DefineFlagsFor
func DefineFlagsFor(name string) { if plugSet, ok := pluginFlags[name]; ok { plugSet.VisitAll(func(f *flag.Flag) { flag.CommandLine.Var(f.Value, f.Name, f.Usage) }) } }
go
func DefineFlagsFor(name string) { if plugSet, ok := pluginFlags[name]; ok { plugSet.VisitAll(func(f *flag.Flag) { flag.CommandLine.Var(f.Value, f.Name, f.Usage) }) } }
[ "func", "DefineFlagsFor", "(", "name", "string", ")", "{", "if", "plugSet", ",", "ok", ":=", "pluginFlags", "[", "name", "]", ";", "ok", "{", "plugSet", ".", "VisitAll", "(", "func", "(", "f", "*", "flag", ".", "Flag", ")", "{", "flag", ".", "Comma...
// DefineFlagsFor registers defined flags for plugin with given name.
[ "DefineFlagsFor", "registers", "defined", "flags", "for", "plugin", "with", "given", "name", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/config/plugin_config.go#L82-L88
4,577
ligato/cn-infra
config/plugin_config.go
WithExtraFlags
func WithExtraFlags(f func(flags *FlagSet)) Option { return func(o *options) { f(o.flagSet) } }
go
func WithExtraFlags(f func(flags *FlagSet)) Option { return func(o *options) { f(o.flagSet) } }
[ "func", "WithExtraFlags", "(", "f", "func", "(", "flags", "*", "FlagSet", ")", ")", "Option", "{", "return", "func", "(", "o", "*", "options", ")", "{", "f", "(", "o", ".", "flagSet", ")", "\n", "}", "\n", "}" ]
// WithExtraFlags is an option to define additional flags for plugin in ForPlugin.
[ "WithExtraFlags", "is", "an", "option", "to", "define", "additional", "flags", "for", "plugin", "in", "ForPlugin", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/config/plugin_config.go#L118-L122
4,578
ligato/cn-infra
config/plugin_config.go
Dir
func Dir() (dir string, err error) { if flg := flag.CommandLine.Lookup(DirFlag); flg != nil { val := flg.Value.String() if strings.HasPrefix(val, ".") { cwd, err := os.Getwd() if err != nil { return cwd, err } return filepath.Join(cwd, val), nil } return val, nil } return "", nil }
go
func Dir() (dir string, err error) { if flg := flag.CommandLine.Lookup(DirFlag); flg != nil { val := flg.Value.String() if strings.HasPrefix(val, ".") { cwd, err := os.Getwd() if err != nil { return cwd, err } return filepath.Join(cwd, val), nil } return val, nil } return "", nil }
[ "func", "Dir", "(", ")", "(", "dir", "string", ",", "err", "error", ")", "{", "if", "flg", ":=", "flag", ".", "CommandLine", ".", "Lookup", "(", "DirFlag", ")", ";", "flg", "!=", "nil", "{", "val", ":=", "flg", ".", "Value", ".", "String", "(", ...
// Dir returns config directory by evaluating the flag DirFlag. It interprets "." as current working directory.
[ "Dir", "returns", "config", "directory", "by", "evaluating", "the", "flag", "DirFlag", ".", "It", "interprets", ".", "as", "current", "working", "directory", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/config/plugin_config.go#L154-L167
4,579
ligato/cn-infra
config/plugin_config.go
LoadValue
func (p *pluginConfig) LoadValue(config interface{}) (found bool, err error) { cfgName := p.GetConfigName() if cfgName == "" { return false, nil } // TODO: switch to Viper (possible to have one huge config file) err = ParseConfigFromYamlFile(cfgName, config) if err != nil { return false, err } return true, nil }
go
func (p *pluginConfig) LoadValue(config interface{}) (found bool, err error) { cfgName := p.GetConfigName() if cfgName == "" { return false, nil } // TODO: switch to Viper (possible to have one huge config file) err = ParseConfigFromYamlFile(cfgName, config) if err != nil { return false, err } return true, nil }
[ "func", "(", "p", "*", "pluginConfig", ")", "LoadValue", "(", "config", "interface", "{", "}", ")", "(", "found", "bool", ",", "err", "error", ")", "{", "cfgName", ":=", "p", ".", "GetConfigName", "(", ")", "\n", "if", "cfgName", "==", "\"", "\"", ...
// LoadValue binds the configuration to config method argument.
[ "LoadValue", "binds", "the", "configuration", "to", "config", "method", "argument", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/config/plugin_config.go#L176-L189
4,580
ligato/cn-infra
db/keyval/filedb/decoder/mock_decoder.go
NewDecoderMock
func NewDecoderMock() *Mock { return &Mock{ responses: make([]*WhenResp, 0), eventChan: make(chan fsnotify.Event), } }
go
func NewDecoderMock() *Mock { return &Mock{ responses: make([]*WhenResp, 0), eventChan: make(chan fsnotify.Event), } }
[ "func", "NewDecoderMock", "(", ")", "*", "Mock", "{", "return", "&", "Mock", "{", "responses", ":", "make", "(", "[", "]", "*", "WhenResp", ",", "0", ")", ",", "eventChan", ":", "make", "(", "chan", "fsnotify", ".", "Event", ")", ",", "}", "\n", ...
// NewDecoderMock creates new instance of the mock and initializes response list
[ "NewDecoderMock", "creates", "new", "instance", "of", "the", "mock", "and", "initializes", "response", "list" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/decoder/mock_decoder.go#L28-L33
4,581
ligato/cn-infra
db/keyval/filedb/decoder/mock_decoder.go
When
func (mock *Mock) When(methodName string) *WhenResp { resp := &WhenResp{ methodName: methodName, } mock.responses = append(mock.responses, resp) return resp }
go
func (mock *Mock) When(methodName string) *WhenResp { resp := &WhenResp{ methodName: methodName, } mock.responses = append(mock.responses, resp) return resp }
[ "func", "(", "mock", "*", "Mock", ")", "When", "(", "methodName", "string", ")", "*", "WhenResp", "{", "resp", ":=", "&", "WhenResp", "{", "methodName", ":", "methodName", ",", "}", "\n", "mock", ".", "responses", "=", "append", "(", "mock", ".", "re...
// When defines name of the related method. It creates a new instance of WhenResp with provided method name and // stores it to the mock.
[ "When", "defines", "name", "of", "the", "related", "method", ".", "It", "creates", "a", "new", "instance", "of", "WhenResp", "with", "provided", "method", "name", "and", "stores", "it", "to", "the", "mock", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/decoder/mock_decoder.go#L43-L49
4,582
ligato/cn-infra
db/keyval/filedb/decoder/mock_decoder.go
getReturnValues
func (mock *Mock) getReturnValues(name string) (response []interface{}) { for i, resp := range mock.responses { if resp.methodName == name { // Remove used response but retain order mock.responses = append(mock.responses[:i], mock.responses[i+1:]...) return resp.items } } // Return empty response return }
go
func (mock *Mock) getReturnValues(name string) (response []interface{}) { for i, resp := range mock.responses { if resp.methodName == name { // Remove used response but retain order mock.responses = append(mock.responses[:i], mock.responses[i+1:]...) return resp.items } } // Return empty response return }
[ "func", "(", "mock", "*", "Mock", ")", "getReturnValues", "(", "name", "string", ")", "(", "response", "[", "]", "interface", "{", "}", ")", "{", "for", "i", ",", "resp", ":=", "range", "mock", ".", "responses", "{", "if", "resp", ".", "methodName", ...
// Auxiliary method returns next return value for provided method as generic type
[ "Auxiliary", "method", "returns", "next", "return", "value", "for", "provided", "method", "as", "generic", "type" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/decoder/mock_decoder.go#L68-L78
4,583
ligato/cn-infra
db/keyval/filedb/decoder/mock_decoder.go
IsProcessable
func (mock *Mock) IsProcessable(file string) bool { items := mock.getReturnValues("IsProcessable") return items[0].(bool) }
go
func (mock *Mock) IsProcessable(file string) bool { items := mock.getReturnValues("IsProcessable") return items[0].(bool) }
[ "func", "(", "mock", "*", "Mock", ")", "IsProcessable", "(", "file", "string", ")", "bool", "{", "items", ":=", "mock", ".", "getReturnValues", "(", "\"", "\"", ")", "\n", "return", "items", "[", "0", "]", ".", "(", "bool", ")", "\n", "}" ]
// IsProcessable mocks original method
[ "IsProcessable", "mocks", "original", "method" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/decoder/mock_decoder.go#L81-L84
4,584
ligato/cn-infra
db/keyval/filedb/decoder/mock_decoder.go
Encode
func (mock *Mock) Encode(data []*FileDataEntry) ([]byte, error) { items := mock.getReturnValues("Decode") if len(items) == 1 { switch typed := items[0].(type) { case []byte: return typed, nil case error: return []byte{}, typed } } else if len(items) == 2 { return items[0].([]byte), items[1].(error) } return []byte{}, nil }
go
func (mock *Mock) Encode(data []*FileDataEntry) ([]byte, error) { items := mock.getReturnValues("Decode") if len(items) == 1 { switch typed := items[0].(type) { case []byte: return typed, nil case error: return []byte{}, typed } } else if len(items) == 2 { return items[0].([]byte), items[1].(error) } return []byte{}, nil }
[ "func", "(", "mock", "*", "Mock", ")", "Encode", "(", "data", "[", "]", "*", "FileDataEntry", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "items", ":=", "mock", ".", "getReturnValues", "(", "\"", "\"", ")", "\n", "if", "len", "(", "items"...
// Encode mocks original method
[ "Encode", "mocks", "original", "method" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/decoder/mock_decoder.go#L87-L100
4,585
ligato/cn-infra
db/keyval/filedb/decoder/mock_decoder.go
Decode
func (mock *Mock) Decode(data []byte) ([]*FileDataEntry, error) { items := mock.getReturnValues("Decode") if len(items) == 1 { switch typed := items[0].(type) { case []*FileDataEntry: return typed, nil case error: return []*FileDataEntry{}, typed } } else if len(items) == 2 { return items[0].([]*FileDataEntry), items[1].(error) } return []*FileDataEntry{}, nil }
go
func (mock *Mock) Decode(data []byte) ([]*FileDataEntry, error) { items := mock.getReturnValues("Decode") if len(items) == 1 { switch typed := items[0].(type) { case []*FileDataEntry: return typed, nil case error: return []*FileDataEntry{}, typed } } else if len(items) == 2 { return items[0].([]*FileDataEntry), items[1].(error) } return []*FileDataEntry{}, nil }
[ "func", "(", "mock", "*", "Mock", ")", "Decode", "(", "data", "[", "]", "byte", ")", "(", "[", "]", "*", "FileDataEntry", ",", "error", ")", "{", "items", ":=", "mock", ".", "getReturnValues", "(", "\"", "\"", ")", "\n", "if", "len", "(", "items"...
// Decode mocks original method
[ "Decode", "mocks", "original", "method" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/decoder/mock_decoder.go#L103-L116
4,586
ligato/cn-infra
rpc/grpc/plugin_impl_grpc.go
Init
func (p *Plugin) Init() (err error) { // Get GRPC configuration file if p.Config == nil { p.Config, err = p.getGrpcConfig() if err != nil || p.disabled { return err } } // Prepare GRPC server if p.grpcServer == nil { opts := p.Config.getGrpcOptions() if p.tlsConfig != nil { opts = append(opts, grpc.Creds(credentials.NewTLS(p.tlsConfig))) } if p.auther != nil { p.Log.Info("Token authentication for gRPC enabled") opts = append(opts, grpc.StreamInterceptor(grpc_auth.StreamServerInterceptor(p.auther.Authenticate))) opts = append(opts, grpc.UnaryInterceptor(grpc_auth.UnaryServerInterceptor(p.auther.Authenticate))) } p.grpcServer = grpc.NewServer(opts...) //grpclog.SetLogger(p.Log.NewLogger("grpc-server")) } return nil }
go
func (p *Plugin) Init() (err error) { // Get GRPC configuration file if p.Config == nil { p.Config, err = p.getGrpcConfig() if err != nil || p.disabled { return err } } // Prepare GRPC server if p.grpcServer == nil { opts := p.Config.getGrpcOptions() if p.tlsConfig != nil { opts = append(opts, grpc.Creds(credentials.NewTLS(p.tlsConfig))) } if p.auther != nil { p.Log.Info("Token authentication for gRPC enabled") opts = append(opts, grpc.StreamInterceptor(grpc_auth.StreamServerInterceptor(p.auther.Authenticate))) opts = append(opts, grpc.UnaryInterceptor(grpc_auth.UnaryServerInterceptor(p.auther.Authenticate))) } p.grpcServer = grpc.NewServer(opts...) //grpclog.SetLogger(p.Log.NewLogger("grpc-server")) } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Init", "(", ")", "(", "err", "error", ")", "{", "// Get GRPC configuration file", "if", "p", ".", "Config", "==", "nil", "{", "p", ".", "Config", ",", "err", "=", "p", ".", "getGrpcConfig", "(", ")", "\n", "if...
// Init prepares GRPC netListener for registration of individual service
[ "Init", "prepares", "GRPC", "netListener", "for", "registration", "of", "individual", "service" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/grpc/plugin_impl_grpc.go#L55-L81
4,587
ligato/cn-infra
rpc/grpc/plugin_impl_grpc.go
AfterInit
func (p *Plugin) AfterInit() (err error) { if p.disabled { return nil } if p.Deps.HTTP != nil { p.Log.Infof("exposing GRPC services via HTTP (port %v) on: /service", strconv.Itoa(p.Deps.HTTP.GetPort())) p.Deps.HTTP.RegisterHTTPHandler("/service", func(formatter *render.Render) http.HandlerFunc { return p.grpcServer.ServeHTTP }, "GET", "PUT", "POST") } else { p.Log.Infof("HTTP not set, skip exposing GRPC services") } // Start GRPC listener p.netListener, err = ListenAndServe(p.Config, p.grpcServer) if err != nil { return err } p.Log.Infof("Listening GRPC on: %v", p.Config.Endpoint) return nil }
go
func (p *Plugin) AfterInit() (err error) { if p.disabled { return nil } if p.Deps.HTTP != nil { p.Log.Infof("exposing GRPC services via HTTP (port %v) on: /service", strconv.Itoa(p.Deps.HTTP.GetPort())) p.Deps.HTTP.RegisterHTTPHandler("/service", func(formatter *render.Render) http.HandlerFunc { return p.grpcServer.ServeHTTP }, "GET", "PUT", "POST") } else { p.Log.Infof("HTTP not set, skip exposing GRPC services") } // Start GRPC listener p.netListener, err = ListenAndServe(p.Config, p.grpcServer) if err != nil { return err } p.Log.Infof("Listening GRPC on: %v", p.Config.Endpoint) return nil }
[ "func", "(", "p", "*", "Plugin", ")", "AfterInit", "(", ")", "(", "err", "error", ")", "{", "if", "p", ".", "disabled", "{", "return", "nil", "\n", "}", "\n\n", "if", "p", ".", "Deps", ".", "HTTP", "!=", "nil", "{", "p", ".", "Log", ".", "Inf...
// AfterInit starts the HTTP netListener.
[ "AfterInit", "starts", "the", "HTTP", "netListener", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/grpc/plugin_impl_grpc.go#L84-L107
4,588
ligato/cn-infra
rpc/grpc/plugin_impl_grpc.go
Close
func (p *Plugin) Close() error { if p.grpcServer != nil { p.grpcServer.Stop() } return nil }
go
func (p *Plugin) Close() error { if p.grpcServer != nil { p.grpcServer.Stop() } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Close", "(", ")", "error", "{", "if", "p", ".", "grpcServer", "!=", "nil", "{", "p", ".", "grpcServer", ".", "Stop", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close stops the HTTP netListener.
[ "Close", "stops", "the", "HTTP", "netListener", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/grpc/plugin_impl_grpc.go#L110-L115
4,589
ligato/cn-infra
db/keyval/redis/config.go
ConfigToClient
func ConfigToClient(config interface{}) (Client, error) { switch cfg := config.(type) { case NodeConfig: return CreateNodeClient(cfg) case ClusterConfig: return CreateClusterClient(cfg) case SentinelConfig: return CreateSentinelClient(cfg) case nil: return nil, fmt.Errorf("Configuration cannot be nil") } return nil, fmt.Errorf("Unknown configuration type %T", config) }
go
func ConfigToClient(config interface{}) (Client, error) { switch cfg := config.(type) { case NodeConfig: return CreateNodeClient(cfg) case ClusterConfig: return CreateClusterClient(cfg) case SentinelConfig: return CreateSentinelClient(cfg) case nil: return nil, fmt.Errorf("Configuration cannot be nil") } return nil, fmt.Errorf("Unknown configuration type %T", config) }
[ "func", "ConfigToClient", "(", "config", "interface", "{", "}", ")", "(", "Client", ",", "error", ")", "{", "switch", "cfg", ":=", "config", ".", "(", "type", ")", "{", "case", "NodeConfig", ":", "return", "CreateNodeClient", "(", "cfg", ")", "\n", "ca...
// ConfigToClient creates an appropriate client according to the configuration // parameter.
[ "ConfigToClient", "creates", "an", "appropriate", "client", "according", "to", "the", "configuration", "parameter", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/redis/config.go#L191-L203
4,590
ligato/cn-infra
db/keyval/redis/config.go
CreateClusterClient
func CreateClusterClient(config ClusterConfig) (Client, error) { return goredis.NewClusterClient(&goredis.ClusterOptions{ Addrs: config.Endpoints, // Enables read only queries on slave nodes. ReadOnly: config.EnableReadQueryOnSlave, MaxRedirects: config.MaxRedirects, RouteByLatency: config.RouteByLatency, // Optional password. Must match the password specified in the requirepass server configuration option. Password: config.Password, // Dial timeout for establishing new connections. Default is 5 seconds. DialTimeout: config.DialTimeout, // Timeout for socket reads. If reached, commands will fail with a timeout instead of blocking. Default is 3 seconds. ReadTimeout: config.ReadTimeout, // Timeout for socket writes. If reached, commands will fail with a timeout instead of blocking. Default is ReadTimeout. WriteTimeout: config.WriteTimeout, // Maximum number of socket connections. Default is 10 connections per every CPU as reported by runtime.NumCPU. PoolSize: config.Pool.PoolSize, // Amount of time a client waits for connection if all connections are busy before returning an error. Default is ReadTimeout + 1 second. PoolTimeout: config.Pool.PoolTimeout, // Amount of time after which a client closes idle connections. Should be less than server's timeout. Default is 5 minutes. IdleTimeout: config.Pool.IdleTimeout, // Frequency of idle checks. Default is 1 minute. When negative value is set, then idle check is disabled. IdleCheckFrequency: config.Pool.IdleCheckFrequency, // Maximum number of retries before giving up. Default is to not retry failed commands. MaxRetries: 0, // Minimum backoff between each retry. Default is 8 milliseconds; -1 disables backoff. MinRetryBackoff: 0, // Maximum backoff between each retry. Default is 512 milliseconds; -1 disables backoff. MaxRetryBackoff: 0, // Hook that is called when new connection is established // OnConnect func(*Conn) error }), nil }
go
func CreateClusterClient(config ClusterConfig) (Client, error) { return goredis.NewClusterClient(&goredis.ClusterOptions{ Addrs: config.Endpoints, // Enables read only queries on slave nodes. ReadOnly: config.EnableReadQueryOnSlave, MaxRedirects: config.MaxRedirects, RouteByLatency: config.RouteByLatency, // Optional password. Must match the password specified in the requirepass server configuration option. Password: config.Password, // Dial timeout for establishing new connections. Default is 5 seconds. DialTimeout: config.DialTimeout, // Timeout for socket reads. If reached, commands will fail with a timeout instead of blocking. Default is 3 seconds. ReadTimeout: config.ReadTimeout, // Timeout for socket writes. If reached, commands will fail with a timeout instead of blocking. Default is ReadTimeout. WriteTimeout: config.WriteTimeout, // Maximum number of socket connections. Default is 10 connections per every CPU as reported by runtime.NumCPU. PoolSize: config.Pool.PoolSize, // Amount of time a client waits for connection if all connections are busy before returning an error. Default is ReadTimeout + 1 second. PoolTimeout: config.Pool.PoolTimeout, // Amount of time after which a client closes idle connections. Should be less than server's timeout. Default is 5 minutes. IdleTimeout: config.Pool.IdleTimeout, // Frequency of idle checks. Default is 1 minute. When negative value is set, then idle check is disabled. IdleCheckFrequency: config.Pool.IdleCheckFrequency, // Maximum number of retries before giving up. Default is to not retry failed commands. MaxRetries: 0, // Minimum backoff between each retry. Default is 8 milliseconds; -1 disables backoff. MinRetryBackoff: 0, // Maximum backoff between each retry. Default is 512 milliseconds; -1 disables backoff. MaxRetryBackoff: 0, // Hook that is called when new connection is established // OnConnect func(*Conn) error }), nil }
[ "func", "CreateClusterClient", "(", "config", "ClusterConfig", ")", "(", "Client", ",", "error", ")", "{", "return", "goredis", ".", "NewClusterClient", "(", "&", "goredis", ".", "ClusterOptions", "{", "Addrs", ":", "config", ".", "Endpoints", ",", "// Enables...
// CreateClusterClient Creates a client that will connect to a redis cluster.
[ "CreateClusterClient", "Creates", "a", "client", "that", "will", "connect", "to", "a", "redis", "cluster", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/redis/config.go#L263-L302
4,591
ligato/cn-infra
db/keyval/redis/config.go
CreateSentinelClient
func CreateSentinelClient(config SentinelConfig) (Client, error) { return goredis.NewFailoverClient(&goredis.FailoverOptions{ SentinelAddrs: config.Endpoints, DB: config.DB, MasterName: config.MasterName, // Optional password. Must match the password specified in the requirepass server configuration option. Password: config.Password, // Dial timeout for establishing new connections. Default is 5 seconds. DialTimeout: config.DialTimeout, // Timeout for socket reads. If reached, commands will fail with a timeout instead of blocking. Default is 3 seconds. ReadTimeout: config.ReadTimeout, // Timeout for socket writes. If reached, commands will fail with a timeout instead of blocking. Default is ReadTimeout. WriteTimeout: config.WriteTimeout, // Maximum number of socket connections. Default is 10 connections per every CPU as reported by runtime.NumCPU. PoolSize: config.Pool.PoolSize, // Amount of time a client waits for connection if all connections are busy before returning an error. Default is ReadTimeout + 1 second. PoolTimeout: config.Pool.PoolTimeout, // Amount of time after which a client closes idle connections. Should be less than server's timeout. Default is 5 minutes. IdleTimeout: config.Pool.IdleTimeout, // Frequency of idle checks. Default is 1 minute. When negative value is set, then idle check is disabled. IdleCheckFrequency: config.Pool.IdleCheckFrequency, // Maximum number of retries before giving up. Default is to not retry failed commands. MaxRetries: 0, // Hook that is called when new connection is established // OnConnect func(*Conn) error }), nil }
go
func CreateSentinelClient(config SentinelConfig) (Client, error) { return goredis.NewFailoverClient(&goredis.FailoverOptions{ SentinelAddrs: config.Endpoints, DB: config.DB, MasterName: config.MasterName, // Optional password. Must match the password specified in the requirepass server configuration option. Password: config.Password, // Dial timeout for establishing new connections. Default is 5 seconds. DialTimeout: config.DialTimeout, // Timeout for socket reads. If reached, commands will fail with a timeout instead of blocking. Default is 3 seconds. ReadTimeout: config.ReadTimeout, // Timeout for socket writes. If reached, commands will fail with a timeout instead of blocking. Default is ReadTimeout. WriteTimeout: config.WriteTimeout, // Maximum number of socket connections. Default is 10 connections per every CPU as reported by runtime.NumCPU. PoolSize: config.Pool.PoolSize, // Amount of time a client waits for connection if all connections are busy before returning an error. Default is ReadTimeout + 1 second. PoolTimeout: config.Pool.PoolTimeout, // Amount of time after which a client closes idle connections. Should be less than server's timeout. Default is 5 minutes. IdleTimeout: config.Pool.IdleTimeout, // Frequency of idle checks. Default is 1 minute. When negative value is set, then idle check is disabled. IdleCheckFrequency: config.Pool.IdleCheckFrequency, // Maximum number of retries before giving up. Default is to not retry failed commands. MaxRetries: 0, // Hook that is called when new connection is established // OnConnect func(*Conn) error }), nil }
[ "func", "CreateSentinelClient", "(", "config", "SentinelConfig", ")", "(", "Client", ",", "error", ")", "{", "return", "goredis", ".", "NewFailoverClient", "(", "&", "goredis", ".", "FailoverOptions", "{", "SentinelAddrs", ":", "config", ".", "Endpoints", ",", ...
// CreateSentinelClient Creates a failover client that will connect to redis sentinels.
[ "CreateSentinelClient", "Creates", "a", "failover", "client", "that", "will", "connect", "to", "redis", "sentinels", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/redis/config.go#L305-L338
4,592
ligato/cn-infra
db/keyval/redis/config.go
LoadConfig
func LoadConfig(configFile string) (cfg interface{}, err error) { b, err := ioutil.ReadFile(configFile) if err != nil { return nil, err } var s SentinelConfig err = yaml.Unmarshal(b, &s) if err != nil { return nil, err } if s.MasterName != "" { return s, nil } n := NodeConfig{} err = yaml.Unmarshal(b, &n) if err != nil { return nil, err } if n.Endpoint != "" { return n, nil } c := ClusterConfig{} err = yaml.Unmarshal(b, &c) if err != nil { return nil, err } return c, nil }
go
func LoadConfig(configFile string) (cfg interface{}, err error) { b, err := ioutil.ReadFile(configFile) if err != nil { return nil, err } var s SentinelConfig err = yaml.Unmarshal(b, &s) if err != nil { return nil, err } if s.MasterName != "" { return s, nil } n := NodeConfig{} err = yaml.Unmarshal(b, &n) if err != nil { return nil, err } if n.Endpoint != "" { return n, nil } c := ClusterConfig{} err = yaml.Unmarshal(b, &c) if err != nil { return nil, err } return c, nil }
[ "func", "LoadConfig", "(", "configFile", "string", ")", "(", "cfg", "interface", "{", "}", ",", "err", "error", ")", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "configFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ...
// LoadConfig Loads the given configFile and returns appropriate config instance.
[ "LoadConfig", "Loads", "the", "given", "configFile", "and", "returns", "appropriate", "config", "instance", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/redis/config.go#L341-L371
4,593
ligato/cn-infra
datasync/grpcsync/plugin_impl_grpsync.go
Init
func (p *Plugin) Init() error { p.Adapter = &syncbase.Adapter{ Watcher: NewAdapter(p.GRPC.GetServer()), } return nil }
go
func (p *Plugin) Init() error { p.Adapter = &syncbase.Adapter{ Watcher: NewAdapter(p.GRPC.GetServer()), } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Init", "(", ")", "error", "{", "p", ".", "Adapter", "=", "&", "syncbase", ".", "Adapter", "{", "Watcher", ":", "NewAdapter", "(", "p", ".", "GRPC", ".", "GetServer", "(", ")", ")", ",", "}", "\n", "return", ...
// Init registers new gRPC service and instantiates plugin.Adapter.
[ "Init", "registers", "new", "gRPC", "service", "and", "instantiates", "plugin", ".", "Adapter", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/grpcsync/plugin_impl_grpsync.go#L38-L43
4,594
ligato/cn-infra
health/statuscheck/pluginstatusmap/plugin_status_map.go
NewPluginStatusMap
func NewPluginStatusMap(owner infra.PluginName) PluginStatusIdxMapRW { return &pluginStatusMap{ mapping: mem.NewNamedMapping(logrus.DefaultLogger(), "plugin_status", IndexPluginStatus), } }
go
func NewPluginStatusMap(owner infra.PluginName) PluginStatusIdxMapRW { return &pluginStatusMap{ mapping: mem.NewNamedMapping(logrus.DefaultLogger(), "plugin_status", IndexPluginStatus), } }
[ "func", "NewPluginStatusMap", "(", "owner", "infra", ".", "PluginName", ")", "PluginStatusIdxMapRW", "{", "return", "&", "pluginStatusMap", "{", "mapping", ":", "mem", ".", "NewNamedMapping", "(", "logrus", ".", "DefaultLogger", "(", ")", ",", "\"", "\"", ",",...
// NewPluginStatusMap is a constructor for PluginStatusIdxMapRW.
[ "NewPluginStatusMap", "is", "a", "constructor", "for", "PluginStatusIdxMapRW", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/pluginstatusmap/plugin_status_map.go#L52-L56
4,595
ligato/cn-infra
health/statuscheck/pluginstatusmap/plugin_status_map.go
Put
func (swi *pluginStatusMap) Put(pluginName string, pluginStatus *status.PluginStatus) { swi.mapping.Put(pluginName, pluginStatus) }
go
func (swi *pluginStatusMap) Put(pluginName string, pluginStatus *status.PluginStatus) { swi.mapping.Put(pluginName, pluginStatus) }
[ "func", "(", "swi", "*", "pluginStatusMap", ")", "Put", "(", "pluginName", "string", ",", "pluginStatus", "*", "status", ".", "PluginStatus", ")", "{", "swi", ".", "mapping", ".", "Put", "(", "pluginName", ",", "pluginStatus", ")", "\n", "}" ]
// RegisterName adds new item into the name-to-index mapping.
[ "RegisterName", "adds", "new", "item", "into", "the", "name", "-", "to", "-", "index", "mapping", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/pluginstatusmap/plugin_status_map.go#L82-L84
4,596
ligato/cn-infra
health/statuscheck/pluginstatusmap/plugin_status_map.go
IndexPluginStatus
func IndexPluginStatus(data interface{}) map[string][]string { logrus.DefaultLogger().Debug("IndexPluginStatus ", data) indexes := map[string][]string{} pluginStatus, ok := data.(*status.PluginStatus) if !ok || pluginStatus == nil { return indexes } state := pluginStatus.State if state != 0 { indexes[stateIndexKey] = []string{state.String()} } return indexes }
go
func IndexPluginStatus(data interface{}) map[string][]string { logrus.DefaultLogger().Debug("IndexPluginStatus ", data) indexes := map[string][]string{} pluginStatus, ok := data.(*status.PluginStatus) if !ok || pluginStatus == nil { return indexes } state := pluginStatus.State if state != 0 { indexes[stateIndexKey] = []string{state.String()} } return indexes }
[ "func", "IndexPluginStatus", "(", "data", "interface", "{", "}", ")", "map", "[", "string", "]", "[", "]", "string", "{", "logrus", ".", "DefaultLogger", "(", ")", ".", "Debug", "(", "\"", "\"", ",", "data", ")", "\n\n", "indexes", ":=", "map", "[", ...
// IndexPluginStatus creates indexes for plugin states and records the state // passed as untyped data.
[ "IndexPluginStatus", "creates", "indexes", "for", "plugin", "states", "and", "records", "the", "state", "passed", "as", "untyped", "data", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/pluginstatusmap/plugin_status_map.go#L88-L102
4,597
ligato/cn-infra
health/statuscheck/pluginstatusmap/plugin_status_map.go
Delete
func (swi *pluginStatusMap) Delete(pluginName string) (data *status.PluginStatus, exists bool) { meta, exists := swi.mapping.Delete(pluginName) return swi.castdata(meta), exists }
go
func (swi *pluginStatusMap) Delete(pluginName string) (data *status.PluginStatus, exists bool) { meta, exists := swi.mapping.Delete(pluginName) return swi.castdata(meta), exists }
[ "func", "(", "swi", "*", "pluginStatusMap", ")", "Delete", "(", "pluginName", "string", ")", "(", "data", "*", "status", ".", "PluginStatus", ",", "exists", "bool", ")", "{", "meta", ",", "exists", ":=", "swi", ".", "mapping", ".", "Delete", "(", "plug...
// UnregisterName removes an item identified by name from mapping
[ "UnregisterName", "removes", "an", "item", "identified", "by", "name", "from", "mapping" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/pluginstatusmap/plugin_status_map.go#L105-L108
4,598
ligato/cn-infra
health/statuscheck/pluginstatusmap/plugin_status_map.go
LookupByState
func (swi *pluginStatusMap) LookupByState(state status.OperationalState) []string { return swi.mapping.ListNames(stateIndexKey, state.String()) }
go
func (swi *pluginStatusMap) LookupByState(state status.OperationalState) []string { return swi.mapping.ListNames(stateIndexKey, state.String()) }
[ "func", "(", "swi", "*", "pluginStatusMap", ")", "LookupByState", "(", "state", "status", ".", "OperationalState", ")", "[", "]", "string", "{", "return", "swi", ".", "mapping", ".", "ListNames", "(", "stateIndexKey", ",", "state", ".", "String", "(", ")",...
// LookupNameByIP returns names of items that contains given IP address in Value
[ "LookupNameByIP", "returns", "names", "of", "items", "that", "contains", "given", "IP", "address", "in", "Value" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/pluginstatusmap/plugin_status_map.go#L120-L122
4,599
ligato/cn-infra
health/statuscheck/pluginstatusmap/plugin_status_map.go
WatchNameToIdx
func (swi *pluginStatusMap) WatchNameToIdx(subscriber infra.PluginName, pluginChannel chan PluginStatusEvent) { swi.mapping.Watch(string(subscriber), func(event idxmap.NamedMappingGenericEvent) { pluginChannel <- PluginStatusEvent{ NamedMappingEvent: event.NamedMappingEvent, Value: swi.castdata(event.Value), } }) }
go
func (swi *pluginStatusMap) WatchNameToIdx(subscriber infra.PluginName, pluginChannel chan PluginStatusEvent) { swi.mapping.Watch(string(subscriber), func(event idxmap.NamedMappingGenericEvent) { pluginChannel <- PluginStatusEvent{ NamedMappingEvent: event.NamedMappingEvent, Value: swi.castdata(event.Value), } }) }
[ "func", "(", "swi", "*", "pluginStatusMap", ")", "WatchNameToIdx", "(", "subscriber", "infra", ".", "PluginName", ",", "pluginChannel", "chan", "PluginStatusEvent", ")", "{", "swi", ".", "mapping", ".", "Watch", "(", "string", "(", "subscriber", ")", ",", "f...
// WatchNameToIdx allows to subscribe for watching changes in pluginStatusMap mapping
[ "WatchNameToIdx", "allows", "to", "subscribe", "for", "watching", "changes", "in", "pluginStatusMap", "mapping" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/statuscheck/pluginstatusmap/plugin_status_map.go#L133-L140