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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
4,700 | ligato/cn-infra | db/keyval/proto_serializer.go | Marshal | func (sp *SerializerProto) Marshal(message proto.Message) ([]byte, error) {
return proto.Marshal(message)
} | go | func (sp *SerializerProto) Marshal(message proto.Message) ([]byte, error) {
return proto.Marshal(message)
} | [
"func",
"(",
"sp",
"*",
"SerializerProto",
")",
"Marshal",
"(",
"message",
"proto",
".",
"Message",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"proto",
".",
"Marshal",
"(",
"message",
")",
"\n",
"}"
] | // Marshal serializes data from proto message to the slice of bytes using proto
// marshaller. | [
"Marshal",
"serializes",
"data",
"from",
"proto",
"message",
"to",
"the",
"slice",
"of",
"bytes",
"using",
"proto",
"marshaller",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/proto_serializer.go#L48-L50 |
4,701 | ligato/cn-infra | db/keyval/proto_serializer.go | Unmarshal | func (sj *SerializerJSON) Unmarshal(data []byte, protoData proto.Message) error {
return jsonpb.Unmarshal(bytes.NewBuffer(data), protoData)
} | go | func (sj *SerializerJSON) Unmarshal(data []byte, protoData proto.Message) error {
return jsonpb.Unmarshal(bytes.NewBuffer(data), protoData)
} | [
"func",
"(",
"sj",
"*",
"SerializerJSON",
")",
"Unmarshal",
"(",
"data",
"[",
"]",
"byte",
",",
"protoData",
"proto",
".",
"Message",
")",
"error",
"{",
"return",
"jsonpb",
".",
"Unmarshal",
"(",
"bytes",
".",
"NewBuffer",
"(",
"data",
")",
",",
"protoData",
")",
"\n",
"}"
] | // Unmarshal deserializes data from slice of bytes into the provided protobuf
// message using jsonpb marshaller to correctly unmarshal protobuf data. | [
"Unmarshal",
"deserializes",
"data",
"from",
"slice",
"of",
"bytes",
"into",
"the",
"provided",
"protobuf",
"message",
"using",
"jsonpb",
"marshaller",
"to",
"correctly",
"unmarshal",
"protobuf",
"data",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/proto_serializer.go#L57-L59 |
4,702 | ligato/cn-infra | db/keyval/proto_serializer.go | Marshal | func (sj *SerializerJSON) Marshal(message proto.Message) ([]byte, error) {
if message == nil {
return []byte("null"), nil
}
var buf bytes.Buffer
if err := DefaultMarshaler.Marshal(&buf, message); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func (sj *SerializerJSON) Marshal(message proto.Message) ([]byte, error) {
if message == nil {
return []byte("null"), nil
}
var buf bytes.Buffer
if err := DefaultMarshaler.Marshal(&buf, message); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"(",
"sj",
"*",
"SerializerJSON",
")",
"Marshal",
"(",
"message",
"proto",
".",
"Message",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"message",
"==",
"nil",
"{",
"return",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
",",
"nil",
"\n",
"}",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"if",
"err",
":=",
"DefaultMarshaler",
".",
"Marshal",
"(",
"&",
"buf",
",",
"message",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // Marshal serializes proto message to the slice of bytes using
// jsonpb marshaller to correctly marshal protobuf data. | [
"Marshal",
"serializes",
"proto",
"message",
"to",
"the",
"slice",
"of",
"bytes",
"using",
"jsonpb",
"marshaller",
"to",
"correctly",
"marshal",
"protobuf",
"data",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/proto_serializer.go#L63-L72 |
4,703 | ligato/cn-infra | datasync/kvdbsync/watch_impl.go | watchResync | func (keys *watchBrokerKeys) watchResync(resyncReg resync.Registration) {
for resyncStatus := range resyncReg.StatusChan() {
if resyncStatus.ResyncStatus() == resync.Started {
err := keys.resync()
if err != nil {
// We are not able to propagate it somewhere else.
logrus.DefaultLogger().Errorf("getting resync data failed: %v", err)
// TODO NICE-to-HAVE publish the err using the transport asynchronously
}
}
resyncStatus.Ack()
}
} | go | func (keys *watchBrokerKeys) watchResync(resyncReg resync.Registration) {
for resyncStatus := range resyncReg.StatusChan() {
if resyncStatus.ResyncStatus() == resync.Started {
err := keys.resync()
if err != nil {
// We are not able to propagate it somewhere else.
logrus.DefaultLogger().Errorf("getting resync data failed: %v", err)
// TODO NICE-to-HAVE publish the err using the transport asynchronously
}
}
resyncStatus.Ack()
}
} | [
"func",
"(",
"keys",
"*",
"watchBrokerKeys",
")",
"watchResync",
"(",
"resyncReg",
"resync",
".",
"Registration",
")",
"{",
"for",
"resyncStatus",
":=",
"range",
"resyncReg",
".",
"StatusChan",
"(",
")",
"{",
"if",
"resyncStatus",
".",
"ResyncStatus",
"(",
")",
"==",
"resync",
".",
"Started",
"{",
"err",
":=",
"keys",
".",
"resync",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// We are not able to propagate it somewhere else.",
"logrus",
".",
"DefaultLogger",
"(",
")",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"// TODO NICE-to-HAVE publish the err using the transport asynchronously",
"}",
"\n",
"}",
"\n",
"resyncStatus",
".",
"Ack",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // resyncReg.StatusChan == Started => resync | [
"resyncReg",
".",
"StatusChan",
"==",
"Started",
"=",
">",
"resync"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/kvdbsync/watch_impl.go#L95-L107 |
4,704 | ligato/cn-infra | datasync/kvdbsync/watch_impl.go | resyncRev | func (keys *watchBrokerKeys) resyncRev() error {
for _, keyPrefix := range keys.prefixes {
revIt, err := keys.adapter.db.ListValues(keyPrefix)
if err != nil {
return err
}
// if there are data for given prefix, register it
for {
data, stop := revIt.GetNext()
if stop {
break
}
logrus.DefaultLogger().Debugf("registering key found in KV: %q", data.GetKey())
keys.adapter.base.LastRev().PutWithRevision(data.GetKey(),
syncbase.NewKeyVal(data.GetKey(), data, data.GetRevision()))
}
}
return nil
} | go | func (keys *watchBrokerKeys) resyncRev() error {
for _, keyPrefix := range keys.prefixes {
revIt, err := keys.adapter.db.ListValues(keyPrefix)
if err != nil {
return err
}
// if there are data for given prefix, register it
for {
data, stop := revIt.GetNext()
if stop {
break
}
logrus.DefaultLogger().Debugf("registering key found in KV: %q", data.GetKey())
keys.adapter.base.LastRev().PutWithRevision(data.GetKey(),
syncbase.NewKeyVal(data.GetKey(), data, data.GetRevision()))
}
}
return nil
} | [
"func",
"(",
"keys",
"*",
"watchBrokerKeys",
")",
"resyncRev",
"(",
")",
"error",
"{",
"for",
"_",
",",
"keyPrefix",
":=",
"range",
"keys",
".",
"prefixes",
"{",
"revIt",
",",
"err",
":=",
"keys",
".",
"adapter",
".",
"db",
".",
"ListValues",
"(",
"keyPrefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// if there are data for given prefix, register it",
"for",
"{",
"data",
",",
"stop",
":=",
"revIt",
".",
"GetNext",
"(",
")",
"\n",
"if",
"stop",
"{",
"break",
"\n",
"}",
"\n",
"logrus",
".",
"DefaultLogger",
"(",
")",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"data",
".",
"GetKey",
"(",
")",
")",
"\n\n",
"keys",
".",
"adapter",
".",
"base",
".",
"LastRev",
"(",
")",
".",
"PutWithRevision",
"(",
"data",
".",
"GetKey",
"(",
")",
",",
"syncbase",
".",
"NewKeyVal",
"(",
"data",
".",
"GetKey",
"(",
")",
",",
"data",
",",
"data",
".",
"GetRevision",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // ResyncRev fill the PrevRevision map. This step needs to be done even if resync is ommited | [
"ResyncRev",
"fill",
"the",
"PrevRevision",
"map",
".",
"This",
"step",
"needs",
"to",
"be",
"done",
"even",
"if",
"resync",
"is",
"ommited"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/kvdbsync/watch_impl.go#L110-L130 |
4,705 | ligato/cn-infra | logging/logmanager/config.go | NewConf | func NewConf() *Config {
return &Config{
DefaultLevel: "",
Loggers: []LoggerConfig{},
Hooks: make(map[string]HookConfig),
}
} | go | func NewConf() *Config {
return &Config{
DefaultLevel: "",
Loggers: []LoggerConfig{},
Hooks: make(map[string]HookConfig),
}
} | [
"func",
"NewConf",
"(",
")",
"*",
"Config",
"{",
"return",
"&",
"Config",
"{",
"DefaultLevel",
":",
"\"",
"\"",
",",
"Loggers",
":",
"[",
"]",
"LoggerConfig",
"{",
"}",
",",
"Hooks",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"HookConfig",
")",
",",
"}",
"\n",
"}"
] | // NewConf creates default configuration with InfoLevel & empty loggers.
// Suitable also for usage in flavor to programmatically specify default behavior. | [
"NewConf",
"creates",
"default",
"configuration",
"with",
"InfoLevel",
"&",
"empty",
"loggers",
".",
"Suitable",
"also",
"for",
"usage",
"in",
"flavor",
"to",
"programmatically",
"specify",
"default",
"behavior",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logmanager/config.go#L5-L11 |
4,706 | ligato/cn-infra | db/keyval/filedb/database/database.go | Add | func (c *DbClient) Add(path string, entry *decoder.FileDataEntry) {
c.Lock()
defer c.Unlock()
if entry == nil {
return
}
fileData, ok := c.db[path]
if ok {
value, ok := fileData[entry.Key]
if ok {
if !bytes.Equal(value.data, entry.Value) {
rev := value.rev + 1
fileData[entry.Key] = &dbEntry{entry.Value, rev}
}
} else {
fileData[entry.Key] = &dbEntry{entry.Value, initialRev}
}
} else {
fileData = map[string]*dbEntry{entry.Key: {entry.Value, initialRev}}
}
c.db[path] = fileData
} | go | func (c *DbClient) Add(path string, entry *decoder.FileDataEntry) {
c.Lock()
defer c.Unlock()
if entry == nil {
return
}
fileData, ok := c.db[path]
if ok {
value, ok := fileData[entry.Key]
if ok {
if !bytes.Equal(value.data, entry.Value) {
rev := value.rev + 1
fileData[entry.Key] = &dbEntry{entry.Value, rev}
}
} else {
fileData[entry.Key] = &dbEntry{entry.Value, initialRev}
}
} else {
fileData = map[string]*dbEntry{entry.Key: {entry.Value, initialRev}}
}
c.db[path] = fileData
} | [
"func",
"(",
"c",
"*",
"DbClient",
")",
"Add",
"(",
"path",
"string",
",",
"entry",
"*",
"decoder",
".",
"FileDataEntry",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"entry",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"fileData",
",",
"ok",
":=",
"c",
".",
"db",
"[",
"path",
"]",
"\n",
"if",
"ok",
"{",
"value",
",",
"ok",
":=",
"fileData",
"[",
"entry",
".",
"Key",
"]",
"\n",
"if",
"ok",
"{",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"value",
".",
"data",
",",
"entry",
".",
"Value",
")",
"{",
"rev",
":=",
"value",
".",
"rev",
"+",
"1",
"\n",
"fileData",
"[",
"entry",
".",
"Key",
"]",
"=",
"&",
"dbEntry",
"{",
"entry",
".",
"Value",
",",
"rev",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"fileData",
"[",
"entry",
".",
"Key",
"]",
"=",
"&",
"dbEntry",
"{",
"entry",
".",
"Value",
",",
"initialRev",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"fileData",
"=",
"map",
"[",
"string",
"]",
"*",
"dbEntry",
"{",
"entry",
".",
"Key",
":",
"{",
"entry",
".",
"Value",
",",
"initialRev",
"}",
"}",
"\n",
"}",
"\n\n",
"c",
".",
"db",
"[",
"path",
"]",
"=",
"fileData",
"\n",
"}"
] | // Add puts new entry to the database, or updates the old one if given key already exists | [
"Add",
"puts",
"new",
"entry",
"to",
"the",
"database",
"or",
"updates",
"the",
"old",
"one",
"if",
"given",
"key",
"already",
"exists"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/database/database.go#L64-L88 |
4,707 | ligato/cn-infra | db/keyval/filedb/database/database.go | Delete | func (c *DbClient) Delete(path, key string) {
c.Lock()
defer c.Unlock()
fileData, ok := c.db[path]
if !ok {
return
}
delete(fileData, key)
} | go | func (c *DbClient) Delete(path, key string) {
c.Lock()
defer c.Unlock()
fileData, ok := c.db[path]
if !ok {
return
}
delete(fileData, key)
} | [
"func",
"(",
"c",
"*",
"DbClient",
")",
"Delete",
"(",
"path",
",",
"key",
"string",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"fileData",
",",
"ok",
":=",
"c",
".",
"db",
"[",
"path",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"delete",
"(",
"fileData",
",",
"key",
")",
"\n",
"}"
] | // Delete removes key in given path. | [
"Delete",
"removes",
"key",
"in",
"given",
"path",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/database/database.go#L91-L100 |
4,708 | ligato/cn-infra | db/keyval/filedb/database/database.go | DeleteFile | func (c *DbClient) DeleteFile(path string) {
c.Lock()
defer c.Unlock()
delete(c.db, path)
} | go | func (c *DbClient) DeleteFile(path string) {
c.Lock()
defer c.Unlock()
delete(c.db, path)
} | [
"func",
"(",
"c",
"*",
"DbClient",
")",
"DeleteFile",
"(",
"path",
"string",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"delete",
"(",
"c",
".",
"db",
",",
"path",
")",
"\n",
"}"
] | // DeleteFile removes file entry including all keys within | [
"DeleteFile",
"removes",
"file",
"entry",
"including",
"all",
"keys",
"within"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/database/database.go#L103-L108 |
4,709 | ligato/cn-infra | db/keyval/filedb/database/database.go | GetDataForPrefix | func (c *DbClient) GetDataForPrefix(prefix string) []*decoder.FileDataEntry {
c.Lock()
defer c.Unlock()
var keyValues []*decoder.FileDataEntry
for _, file := range c.db {
for key, value := range file {
if strings.HasPrefix(key, prefix) {
keyValues = append(keyValues, &decoder.FileDataEntry{
Key: key,
Value: value.data,
})
}
}
}
return keyValues
} | go | func (c *DbClient) GetDataForPrefix(prefix string) []*decoder.FileDataEntry {
c.Lock()
defer c.Unlock()
var keyValues []*decoder.FileDataEntry
for _, file := range c.db {
for key, value := range file {
if strings.HasPrefix(key, prefix) {
keyValues = append(keyValues, &decoder.FileDataEntry{
Key: key,
Value: value.data,
})
}
}
}
return keyValues
} | [
"func",
"(",
"c",
"*",
"DbClient",
")",
"GetDataForPrefix",
"(",
"prefix",
"string",
")",
"[",
"]",
"*",
"decoder",
".",
"FileDataEntry",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"keyValues",
"[",
"]",
"*",
"decoder",
".",
"FileDataEntry",
"\n",
"for",
"_",
",",
"file",
":=",
"range",
"c",
".",
"db",
"{",
"for",
"key",
",",
"value",
":=",
"range",
"file",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"prefix",
")",
"{",
"keyValues",
"=",
"append",
"(",
"keyValues",
",",
"&",
"decoder",
".",
"FileDataEntry",
"{",
"Key",
":",
"key",
",",
"Value",
":",
"value",
".",
"data",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"keyValues",
"\n",
"}"
] | // GetDataForPrefix returns all values which match provided prefix | [
"GetDataForPrefix",
"returns",
"all",
"values",
"which",
"match",
"provided",
"prefix"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/database/database.go#L111-L127 |
4,710 | ligato/cn-infra | db/keyval/filedb/database/database.go | GetDataForFile | func (c *DbClient) GetDataForFile(path string) []*decoder.FileDataEntry {
c.Lock()
defer c.Unlock()
var keyValues []*decoder.FileDataEntry
if dbKeyValues, ok := c.db[path]; ok {
for key, value := range dbKeyValues {
keyValues = append(keyValues, &decoder.FileDataEntry{
Key: key,
Value: value.data,
})
}
}
return keyValues
} | go | func (c *DbClient) GetDataForFile(path string) []*decoder.FileDataEntry {
c.Lock()
defer c.Unlock()
var keyValues []*decoder.FileDataEntry
if dbKeyValues, ok := c.db[path]; ok {
for key, value := range dbKeyValues {
keyValues = append(keyValues, &decoder.FileDataEntry{
Key: key,
Value: value.data,
})
}
}
return keyValues
} | [
"func",
"(",
"c",
"*",
"DbClient",
")",
"GetDataForFile",
"(",
"path",
"string",
")",
"[",
"]",
"*",
"decoder",
".",
"FileDataEntry",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"keyValues",
"[",
"]",
"*",
"decoder",
".",
"FileDataEntry",
"\n",
"if",
"dbKeyValues",
",",
"ok",
":=",
"c",
".",
"db",
"[",
"path",
"]",
";",
"ok",
"{",
"for",
"key",
",",
"value",
":=",
"range",
"dbKeyValues",
"{",
"keyValues",
"=",
"append",
"(",
"keyValues",
",",
"&",
"decoder",
".",
"FileDataEntry",
"{",
"Key",
":",
"key",
",",
"Value",
":",
"value",
".",
"data",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"keyValues",
"\n",
"}"
] | // GetDataForFile returns a map of key-value entries from given file | [
"GetDataForFile",
"returns",
"a",
"map",
"of",
"key",
"-",
"value",
"entries",
"from",
"given",
"file"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/database/database.go#L130-L144 |
4,711 | ligato/cn-infra | db/keyval/filedb/database/database.go | GetDataForKey | func (c *DbClient) GetDataForKey(key string) (*decoder.FileDataEntry, bool) {
c.Lock()
defer c.Unlock()
for _, file := range c.db {
value, ok := file[key]
if ok {
return &decoder.FileDataEntry{
Key: key,
Value: value.data,
}, true
}
}
return nil, false
} | go | func (c *DbClient) GetDataForKey(key string) (*decoder.FileDataEntry, bool) {
c.Lock()
defer c.Unlock()
for _, file := range c.db {
value, ok := file[key]
if ok {
return &decoder.FileDataEntry{
Key: key,
Value: value.data,
}, true
}
}
return nil, false
} | [
"func",
"(",
"c",
"*",
"DbClient",
")",
"GetDataForKey",
"(",
"key",
"string",
")",
"(",
"*",
"decoder",
".",
"FileDataEntry",
",",
"bool",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"file",
":=",
"range",
"c",
".",
"db",
"{",
"value",
",",
"ok",
":=",
"file",
"[",
"key",
"]",
"\n",
"if",
"ok",
"{",
"return",
"&",
"decoder",
".",
"FileDataEntry",
"{",
"Key",
":",
"key",
",",
"Value",
":",
"value",
".",
"data",
",",
"}",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"false",
"\n",
"}"
] | // GetDataForKey returns data for given key. | [
"GetDataForKey",
"returns",
"data",
"for",
"given",
"key",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/database/database.go#L147-L161 |
4,712 | ligato/cn-infra | db/sql/cassandra/config.go | ConfigToClientConfig | func ConfigToClientConfig(ymlConfig *Config) (*ClientConfig, error) {
timeout := defaultOpTimeout
if ymlConfig.OpTimeout > 0 {
timeout = ymlConfig.OpTimeout
}
connectTimeout := defaultDialTimeout
if ymlConfig.DialTimeout > 0 {
connectTimeout = ymlConfig.DialTimeout
}
reconnectInterval := defaultRedialInterval
if ymlConfig.RedialInterval > 0 {
reconnectInterval = ymlConfig.RedialInterval
}
protoVersion := defaultProtocolVersion
if ymlConfig.ProtocolVersion > 0 {
protoVersion = ymlConfig.ProtocolVersion
}
endpoints, port, err := getEndpointsAndPort(ymlConfig.Endpoints)
if err != nil {
return nil, err
}
var sslOpts *gocql.SslOptions
if ymlConfig.TLS.Enabled {
sslOpts = &gocql.SslOptions{
CaPath: ymlConfig.TLS.CAfile,
CertPath: ymlConfig.TLS.Certfile,
KeyPath: ymlConfig.TLS.Keyfile,
EnableHostVerification: ymlConfig.TLS.EnableHostVerification,
}
}
clientConfig := &gocql.ClusterConfig{
Hosts: endpoints,
Port: port,
Timeout: timeout * time.Millisecond,
ConnectTimeout: connectTimeout * time.Millisecond,
ReconnectInterval: reconnectInterval * time.Second,
ProtoVersion: protoVersion,
SslOpts: sslOpts,
}
cfg := &ClientConfig{ClusterConfig: clientConfig}
return cfg, nil
} | go | func ConfigToClientConfig(ymlConfig *Config) (*ClientConfig, error) {
timeout := defaultOpTimeout
if ymlConfig.OpTimeout > 0 {
timeout = ymlConfig.OpTimeout
}
connectTimeout := defaultDialTimeout
if ymlConfig.DialTimeout > 0 {
connectTimeout = ymlConfig.DialTimeout
}
reconnectInterval := defaultRedialInterval
if ymlConfig.RedialInterval > 0 {
reconnectInterval = ymlConfig.RedialInterval
}
protoVersion := defaultProtocolVersion
if ymlConfig.ProtocolVersion > 0 {
protoVersion = ymlConfig.ProtocolVersion
}
endpoints, port, err := getEndpointsAndPort(ymlConfig.Endpoints)
if err != nil {
return nil, err
}
var sslOpts *gocql.SslOptions
if ymlConfig.TLS.Enabled {
sslOpts = &gocql.SslOptions{
CaPath: ymlConfig.TLS.CAfile,
CertPath: ymlConfig.TLS.Certfile,
KeyPath: ymlConfig.TLS.Keyfile,
EnableHostVerification: ymlConfig.TLS.EnableHostVerification,
}
}
clientConfig := &gocql.ClusterConfig{
Hosts: endpoints,
Port: port,
Timeout: timeout * time.Millisecond,
ConnectTimeout: connectTimeout * time.Millisecond,
ReconnectInterval: reconnectInterval * time.Second,
ProtoVersion: protoVersion,
SslOpts: sslOpts,
}
cfg := &ClientConfig{ClusterConfig: clientConfig}
return cfg, nil
} | [
"func",
"ConfigToClientConfig",
"(",
"ymlConfig",
"*",
"Config",
")",
"(",
"*",
"ClientConfig",
",",
"error",
")",
"{",
"timeout",
":=",
"defaultOpTimeout",
"\n",
"if",
"ymlConfig",
".",
"OpTimeout",
">",
"0",
"{",
"timeout",
"=",
"ymlConfig",
".",
"OpTimeout",
"\n",
"}",
"\n\n",
"connectTimeout",
":=",
"defaultDialTimeout",
"\n",
"if",
"ymlConfig",
".",
"DialTimeout",
">",
"0",
"{",
"connectTimeout",
"=",
"ymlConfig",
".",
"DialTimeout",
"\n",
"}",
"\n\n",
"reconnectInterval",
":=",
"defaultRedialInterval",
"\n",
"if",
"ymlConfig",
".",
"RedialInterval",
">",
"0",
"{",
"reconnectInterval",
"=",
"ymlConfig",
".",
"RedialInterval",
"\n",
"}",
"\n\n",
"protoVersion",
":=",
"defaultProtocolVersion",
"\n",
"if",
"ymlConfig",
".",
"ProtocolVersion",
">",
"0",
"{",
"protoVersion",
"=",
"ymlConfig",
".",
"ProtocolVersion",
"\n",
"}",
"\n\n",
"endpoints",
",",
"port",
",",
"err",
":=",
"getEndpointsAndPort",
"(",
"ymlConfig",
".",
"Endpoints",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"sslOpts",
"*",
"gocql",
".",
"SslOptions",
"\n",
"if",
"ymlConfig",
".",
"TLS",
".",
"Enabled",
"{",
"sslOpts",
"=",
"&",
"gocql",
".",
"SslOptions",
"{",
"CaPath",
":",
"ymlConfig",
".",
"TLS",
".",
"CAfile",
",",
"CertPath",
":",
"ymlConfig",
".",
"TLS",
".",
"Certfile",
",",
"KeyPath",
":",
"ymlConfig",
".",
"TLS",
".",
"Keyfile",
",",
"EnableHostVerification",
":",
"ymlConfig",
".",
"TLS",
".",
"EnableHostVerification",
",",
"}",
"\n",
"}",
"\n\n",
"clientConfig",
":=",
"&",
"gocql",
".",
"ClusterConfig",
"{",
"Hosts",
":",
"endpoints",
",",
"Port",
":",
"port",
",",
"Timeout",
":",
"timeout",
"*",
"time",
".",
"Millisecond",
",",
"ConnectTimeout",
":",
"connectTimeout",
"*",
"time",
".",
"Millisecond",
",",
"ReconnectInterval",
":",
"reconnectInterval",
"*",
"time",
".",
"Second",
",",
"ProtoVersion",
":",
"protoVersion",
",",
"SslOpts",
":",
"sslOpts",
",",
"}",
"\n\n",
"cfg",
":=",
"&",
"ClientConfig",
"{",
"ClusterConfig",
":",
"clientConfig",
"}",
"\n\n",
"return",
"cfg",
",",
"nil",
"\n",
"}"
] | // ConfigToClientConfig transforms the yaml configuration into ClientConfig.
// If the configuration of endpoints is invalid, error ErrInvalidEndpointConfig
// is returned. | [
"ConfigToClientConfig",
"transforms",
"the",
"yaml",
"configuration",
"into",
"ClientConfig",
".",
"If",
"the",
"configuration",
"of",
"endpoints",
"is",
"invalid",
"error",
"ErrInvalidEndpointConfig",
"is",
"returned",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/cassandra/config.go#L78-L128 |
4,713 | ligato/cn-infra | rpc/grpc/listen_and_serve.go | ListenAndServe | func ListenAndServe(cfg *Config, srv *grpc.Server) (netListener net.Listener, err error) {
switch socketType := cfg.getSocketType(); socketType {
case "unix", "unixpacket":
permissions, err := getUnixSocketFilePermissions(cfg.Permission)
if err != nil {
return nil, err
}
if err := checkUnixSocketFileAndDirectory(cfg.Endpoint, cfg.ForceSocketRemoval); err != nil {
return nil, err
}
netListener, err = net.Listen(socketType, cfg.Endpoint)
if err != nil {
return nil, err
}
// Set permissions to the socket file
if err := os.Chmod(cfg.Endpoint, permissions); err != nil {
return nil, err
}
default:
netListener, err = net.Listen(socketType, cfg.Endpoint)
if err != nil {
return nil, err
}
}
go func() {
err := srv.Serve(netListener)
// Serve always returns non-nil error
logging.DefaultLogger.Debugf("GRPC server Serve: %v", err)
}()
return netListener, nil
} | go | func ListenAndServe(cfg *Config, srv *grpc.Server) (netListener net.Listener, err error) {
switch socketType := cfg.getSocketType(); socketType {
case "unix", "unixpacket":
permissions, err := getUnixSocketFilePermissions(cfg.Permission)
if err != nil {
return nil, err
}
if err := checkUnixSocketFileAndDirectory(cfg.Endpoint, cfg.ForceSocketRemoval); err != nil {
return nil, err
}
netListener, err = net.Listen(socketType, cfg.Endpoint)
if err != nil {
return nil, err
}
// Set permissions to the socket file
if err := os.Chmod(cfg.Endpoint, permissions); err != nil {
return nil, err
}
default:
netListener, err = net.Listen(socketType, cfg.Endpoint)
if err != nil {
return nil, err
}
}
go func() {
err := srv.Serve(netListener)
// Serve always returns non-nil error
logging.DefaultLogger.Debugf("GRPC server Serve: %v", err)
}()
return netListener, nil
} | [
"func",
"ListenAndServe",
"(",
"cfg",
"*",
"Config",
",",
"srv",
"*",
"grpc",
".",
"Server",
")",
"(",
"netListener",
"net",
".",
"Listener",
",",
"err",
"error",
")",
"{",
"switch",
"socketType",
":=",
"cfg",
".",
"getSocketType",
"(",
")",
";",
"socketType",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"permissions",
",",
"err",
":=",
"getUnixSocketFilePermissions",
"(",
"cfg",
".",
"Permission",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"checkUnixSocketFileAndDirectory",
"(",
"cfg",
".",
"Endpoint",
",",
"cfg",
".",
"ForceSocketRemoval",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"netListener",
",",
"err",
"=",
"net",
".",
"Listen",
"(",
"socketType",
",",
"cfg",
".",
"Endpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Set permissions to the socket file",
"if",
"err",
":=",
"os",
".",
"Chmod",
"(",
"cfg",
".",
"Endpoint",
",",
"permissions",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"default",
":",
"netListener",
",",
"err",
"=",
"net",
".",
"Listen",
"(",
"socketType",
",",
"cfg",
".",
"Endpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"err",
":=",
"srv",
".",
"Serve",
"(",
"netListener",
")",
"\n",
"// Serve always returns non-nil error",
"logging",
".",
"DefaultLogger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"netListener",
",",
"nil",
"\n",
"}"
] | // ListenAndServe starts configured listener and serving for clients | [
"ListenAndServe",
"starts",
"configured",
"listener",
"and",
"serving",
"for",
"clients"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/grpc/listen_and_serve.go#L29-L63 |
4,714 | ligato/cn-infra | rpc/grpc/listen_and_serve.go | getUnixSocketFilePermissions | func getUnixSocketFilePermissions(permissions int) (os.FileMode, error) {
if permissions > 0 {
if permissions > 7777 {
return 0, fmt.Errorf("incorrect unix socket file/path permission value '%d'", permissions)
}
// Convert to correct mode format
mode, err := strconv.ParseInt(strconv.Itoa(permissions), 8, 32)
if err != nil {
return 0, fmt.Errorf("failed to parse socket file permissions %d", permissions)
}
return os.FileMode(mode), nil
}
return os.ModePerm, nil
} | go | func getUnixSocketFilePermissions(permissions int) (os.FileMode, error) {
if permissions > 0 {
if permissions > 7777 {
return 0, fmt.Errorf("incorrect unix socket file/path permission value '%d'", permissions)
}
// Convert to correct mode format
mode, err := strconv.ParseInt(strconv.Itoa(permissions), 8, 32)
if err != nil {
return 0, fmt.Errorf("failed to parse socket file permissions %d", permissions)
}
return os.FileMode(mode), nil
}
return os.ModePerm, nil
} | [
"func",
"getUnixSocketFilePermissions",
"(",
"permissions",
"int",
")",
"(",
"os",
".",
"FileMode",
",",
"error",
")",
"{",
"if",
"permissions",
">",
"0",
"{",
"if",
"permissions",
">",
"7777",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"permissions",
")",
"\n",
"}",
"\n",
"// Convert to correct mode format",
"mode",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"strconv",
".",
"Itoa",
"(",
"permissions",
")",
",",
"8",
",",
"32",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"permissions",
")",
"\n",
"}",
"\n",
"return",
"os",
".",
"FileMode",
"(",
"mode",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"os",
".",
"ModePerm",
",",
"nil",
"\n",
"}"
] | // Resolve permissions and return FileMode | [
"Resolve",
"permissions",
"and",
"return",
"FileMode"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/grpc/listen_and_serve.go#L66-L79 |
4,715 | ligato/cn-infra | datasync/resync/registration.go | newRegistration | func newRegistration(resyncName string, statusChan chan StatusEvent) *registration {
return ®istration{resyncName: resyncName, statusChan: statusChan}
} | go | func newRegistration(resyncName string, statusChan chan StatusEvent) *registration {
return ®istration{resyncName: resyncName, statusChan: statusChan}
} | [
"func",
"newRegistration",
"(",
"resyncName",
"string",
",",
"statusChan",
"chan",
"StatusEvent",
")",
"*",
"registration",
"{",
"return",
"&",
"registration",
"{",
"resyncName",
":",
"resyncName",
",",
"statusChan",
":",
"statusChan",
"}",
"\n",
"}"
] | // newRegistration is a constructor. | [
"newRegistration",
"is",
"a",
"constructor",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/resync/registration.go#L26-L28 |
4,716 | ligato/cn-infra | datasync/resync/registration.go | newStatusEvent | func newStatusEvent(status Status) *statusEvent {
return &statusEvent{status: status, ackChan: make(chan time.Time)}
} | go | func newStatusEvent(status Status) *statusEvent {
return &statusEvent{status: status, ackChan: make(chan time.Time)}
} | [
"func",
"newStatusEvent",
"(",
"status",
"Status",
")",
"*",
"statusEvent",
"{",
"return",
"&",
"statusEvent",
"{",
"status",
":",
"status",
",",
"ackChan",
":",
"make",
"(",
"chan",
"time",
".",
"Time",
")",
"}",
"\n",
"}"
] | // newStatusEvent is a constructor. | [
"newStatusEvent",
"is",
"a",
"constructor",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/resync/registration.go#L41-L43 |
4,717 | ligato/cn-infra | logging/logrus/registry.go | NewLogRegistry | func NewLogRegistry() logging.Registry {
registry := &logRegistry{
loggers: new(sync.Map),
logLevels: make(map[string]logrus.Level),
defaultLevel: initialLogLvl,
}
// put default logger
registry.putLoggerToMapping(defaultLogger)
return registry
} | go | func NewLogRegistry() logging.Registry {
registry := &logRegistry{
loggers: new(sync.Map),
logLevels: make(map[string]logrus.Level),
defaultLevel: initialLogLvl,
}
// put default logger
registry.putLoggerToMapping(defaultLogger)
return registry
} | [
"func",
"NewLogRegistry",
"(",
")",
"logging",
".",
"Registry",
"{",
"registry",
":=",
"&",
"logRegistry",
"{",
"loggers",
":",
"new",
"(",
"sync",
".",
"Map",
")",
",",
"logLevels",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"logrus",
".",
"Level",
")",
",",
"defaultLevel",
":",
"initialLogLvl",
",",
"}",
"\n",
"// put default logger",
"registry",
".",
"putLoggerToMapping",
"(",
"defaultLogger",
")",
"\n",
"return",
"registry",
"\n",
"}"
] | // NewLogRegistry is a constructor | [
"NewLogRegistry",
"is",
"a",
"constructor"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/registry.go#L46-L55 |
4,718 | ligato/cn-infra | logging/logrus/registry.go | NewLogger | func (lr *logRegistry) NewLogger(name string) logging.Logger {
if existingLogger := lr.getLoggerFromMapping(name); existingLogger != nil {
panic(fmt.Errorf("logger with name '%s' already exists", name))
}
if err := checkLoggerName(name); err != nil {
panic(err)
}
logger := NewLogger(name)
// set initial logger level
if lvl, ok := lr.logLevels[name]; ok {
setLevel(logger, lvl)
} else {
setLevel(logger, lr.defaultLevel)
}
lr.putLoggerToMapping(logger)
// add all defined hooks
for _, hook := range lr.hooks {
logger.std.AddHook(hook)
}
return logger
} | go | func (lr *logRegistry) NewLogger(name string) logging.Logger {
if existingLogger := lr.getLoggerFromMapping(name); existingLogger != nil {
panic(fmt.Errorf("logger with name '%s' already exists", name))
}
if err := checkLoggerName(name); err != nil {
panic(err)
}
logger := NewLogger(name)
// set initial logger level
if lvl, ok := lr.logLevels[name]; ok {
setLevel(logger, lvl)
} else {
setLevel(logger, lr.defaultLevel)
}
lr.putLoggerToMapping(logger)
// add all defined hooks
for _, hook := range lr.hooks {
logger.std.AddHook(hook)
}
return logger
} | [
"func",
"(",
"lr",
"*",
"logRegistry",
")",
"NewLogger",
"(",
"name",
"string",
")",
"logging",
".",
"Logger",
"{",
"if",
"existingLogger",
":=",
"lr",
".",
"getLoggerFromMapping",
"(",
"name",
")",
";",
"existingLogger",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"checkLoggerName",
"(",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"logger",
":=",
"NewLogger",
"(",
"name",
")",
"\n\n",
"// set initial logger level",
"if",
"lvl",
",",
"ok",
":=",
"lr",
".",
"logLevels",
"[",
"name",
"]",
";",
"ok",
"{",
"setLevel",
"(",
"logger",
",",
"lvl",
")",
"\n",
"}",
"else",
"{",
"setLevel",
"(",
"logger",
",",
"lr",
".",
"defaultLevel",
")",
"\n",
"}",
"\n\n",
"lr",
".",
"putLoggerToMapping",
"(",
"logger",
")",
"\n\n",
"// add all defined hooks",
"for",
"_",
",",
"hook",
":=",
"range",
"lr",
".",
"hooks",
"{",
"logger",
".",
"std",
".",
"AddHook",
"(",
"hook",
")",
"\n",
"}",
"\n\n",
"return",
"logger",
"\n",
"}"
] | // NewLogger creates new named Logger instance. Name can be subsequently used to
// refer the logger in registry. | [
"NewLogger",
"creates",
"new",
"named",
"Logger",
"instance",
".",
"Name",
"can",
"be",
"subsequently",
"used",
"to",
"refer",
"the",
"logger",
"in",
"registry",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/registry.go#L80-L105 |
4,719 | ligato/cn-infra | logging/logrus/registry.go | SetLevel | func (lr *logRegistry) SetLevel(logger, level string) error {
lvl, err := logrus.ParseLevel(level)
if err != nil {
return err
}
if logger == "default" {
lr.defaultLevel = lvl
return nil
}
lr.logLevels[logger] = lvl
logVal := lr.getLoggerFromMapping(logger)
if logVal != nil {
defaultLogger.Debugf("setting logger level: %v -> %v", logVal.GetName(), lvl.String())
return setLevel(logVal, lvl)
}
return nil
} | go | func (lr *logRegistry) SetLevel(logger, level string) error {
lvl, err := logrus.ParseLevel(level)
if err != nil {
return err
}
if logger == "default" {
lr.defaultLevel = lvl
return nil
}
lr.logLevels[logger] = lvl
logVal := lr.getLoggerFromMapping(logger)
if logVal != nil {
defaultLogger.Debugf("setting logger level: %v -> %v", logVal.GetName(), lvl.String())
return setLevel(logVal, lvl)
}
return nil
} | [
"func",
"(",
"lr",
"*",
"logRegistry",
")",
"SetLevel",
"(",
"logger",
",",
"level",
"string",
")",
"error",
"{",
"lvl",
",",
"err",
":=",
"logrus",
".",
"ParseLevel",
"(",
"level",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"logger",
"==",
"\"",
"\"",
"{",
"lr",
".",
"defaultLevel",
"=",
"lvl",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"lr",
".",
"logLevels",
"[",
"logger",
"]",
"=",
"lvl",
"\n",
"logVal",
":=",
"lr",
".",
"getLoggerFromMapping",
"(",
"logger",
")",
"\n",
"if",
"logVal",
"!=",
"nil",
"{",
"defaultLogger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"logVal",
".",
"GetName",
"(",
")",
",",
"lvl",
".",
"String",
"(",
")",
")",
"\n",
"return",
"setLevel",
"(",
"logVal",
",",
"lvl",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // SetLevel modifies log level of selected logger in the registry | [
"SetLevel",
"modifies",
"log",
"level",
"of",
"selected",
"logger",
"in",
"the",
"registry"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/registry.go#L159-L175 |
4,720 | ligato/cn-infra | logging/logrus/registry.go | GetLevel | func (lr *logRegistry) GetLevel(logger string) (string, error) {
logVal := lr.getLoggerFromMapping(logger)
if logVal == nil {
return "", fmt.Errorf("logger %s not found", logger)
}
return logVal.GetLevel().String(), nil
} | go | func (lr *logRegistry) GetLevel(logger string) (string, error) {
logVal := lr.getLoggerFromMapping(logger)
if logVal == nil {
return "", fmt.Errorf("logger %s not found", logger)
}
return logVal.GetLevel().String(), nil
} | [
"func",
"(",
"lr",
"*",
"logRegistry",
")",
"GetLevel",
"(",
"logger",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"logVal",
":=",
"lr",
".",
"getLoggerFromMapping",
"(",
"logger",
")",
"\n",
"if",
"logVal",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"logger",
")",
"\n",
"}",
"\n",
"return",
"logVal",
".",
"GetLevel",
"(",
")",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
] | // GetLevel returns the currently set log level of the logger | [
"GetLevel",
"returns",
"the",
"currently",
"set",
"log",
"level",
"of",
"the",
"logger"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/registry.go#L178-L184 |
4,721 | ligato/cn-infra | logging/logrus/registry.go | Lookup | func (lr *logRegistry) Lookup(loggerName string) (logger logging.Logger, found bool) {
loggerInt, found := lr.loggers.Load(loggerName)
if !found {
return nil, false
}
logger, ok := loggerInt.(*Logger)
if ok {
return logger, found
}
panic(fmt.Errorf("cannot cast log value to Logger obj"))
} | go | func (lr *logRegistry) Lookup(loggerName string) (logger logging.Logger, found bool) {
loggerInt, found := lr.loggers.Load(loggerName)
if !found {
return nil, false
}
logger, ok := loggerInt.(*Logger)
if ok {
return logger, found
}
panic(fmt.Errorf("cannot cast log value to Logger obj"))
} | [
"func",
"(",
"lr",
"*",
"logRegistry",
")",
"Lookup",
"(",
"loggerName",
"string",
")",
"(",
"logger",
"logging",
".",
"Logger",
",",
"found",
"bool",
")",
"{",
"loggerInt",
",",
"found",
":=",
"lr",
".",
"loggers",
".",
"Load",
"(",
"loggerName",
")",
"\n",
"if",
"!",
"found",
"{",
"return",
"nil",
",",
"false",
"\n",
"}",
"\n",
"logger",
",",
"ok",
":=",
"loggerInt",
".",
"(",
"*",
"Logger",
")",
"\n",
"if",
"ok",
"{",
"return",
"logger",
",",
"found",
"\n",
"}",
"\n",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // Lookup returns a logger instance identified by name from registry | [
"Lookup",
"returns",
"a",
"logger",
"instance",
"identified",
"by",
"name",
"from",
"registry"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/registry.go#L187-L197 |
4,722 | ligato/cn-infra | logging/logrus/registry.go | ClearRegistry | func (lr *logRegistry) ClearRegistry() {
var wasErr error
// range over logger map and store keys
lr.loggers.Range(func(k, v interface{}) bool {
key, ok := k.(string)
if !ok {
wasErr = fmt.Errorf("cannot cast log map key to string")
// false stops the iteration
return false
}
if key != DefaultLoggerName {
lr.loggers.Delete(key)
}
return true
})
if wasErr != nil {
panic(wasErr)
}
} | go | func (lr *logRegistry) ClearRegistry() {
var wasErr error
// range over logger map and store keys
lr.loggers.Range(func(k, v interface{}) bool {
key, ok := k.(string)
if !ok {
wasErr = fmt.Errorf("cannot cast log map key to string")
// false stops the iteration
return false
}
if key != DefaultLoggerName {
lr.loggers.Delete(key)
}
return true
})
if wasErr != nil {
panic(wasErr)
}
} | [
"func",
"(",
"lr",
"*",
"logRegistry",
")",
"ClearRegistry",
"(",
")",
"{",
"var",
"wasErr",
"error",
"\n\n",
"// range over logger map and store keys",
"lr",
".",
"loggers",
".",
"Range",
"(",
"func",
"(",
"k",
",",
"v",
"interface",
"{",
"}",
")",
"bool",
"{",
"key",
",",
"ok",
":=",
"k",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"wasErr",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"// false stops the iteration",
"return",
"false",
"\n",
"}",
"\n",
"if",
"key",
"!=",
"DefaultLoggerName",
"{",
"lr",
".",
"loggers",
".",
"Delete",
"(",
"key",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
")",
"\n\n",
"if",
"wasErr",
"!=",
"nil",
"{",
"panic",
"(",
"wasErr",
")",
"\n",
"}",
"\n",
"}"
] | // ClearRegistry removes all loggers except the default one from registry | [
"ClearRegistry",
"removes",
"all",
"loggers",
"except",
"the",
"default",
"one",
"from",
"registry"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/registry.go#L200-L220 |
4,723 | ligato/cn-infra | logging/logrus/registry.go | putLoggerToMapping | func (lr *logRegistry) putLoggerToMapping(logger *Logger) {
lr.loggers.Store(logger.name, logger)
} | go | func (lr *logRegistry) putLoggerToMapping(logger *Logger) {
lr.loggers.Store(logger.name, logger)
} | [
"func",
"(",
"lr",
"*",
"logRegistry",
")",
"putLoggerToMapping",
"(",
"logger",
"*",
"Logger",
")",
"{",
"lr",
".",
"loggers",
".",
"Store",
"(",
"logger",
".",
"name",
",",
"logger",
")",
"\n",
"}"
] | // putLoggerToMapping writes logger into map of named loggers | [
"putLoggerToMapping",
"writes",
"logger",
"into",
"map",
"of",
"named",
"loggers"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/registry.go#L223-L225 |
4,724 | ligato/cn-infra | logging/logrus/registry.go | getLoggerFromMapping | func (lr *logRegistry) getLoggerFromMapping(logger string) *Logger {
loggerVal, found := lr.loggers.Load(logger)
if !found {
return nil
}
log, ok := loggerVal.(*Logger)
if ok {
return log
}
panic("cannot cast log value to Logger obj")
} | go | func (lr *logRegistry) getLoggerFromMapping(logger string) *Logger {
loggerVal, found := lr.loggers.Load(logger)
if !found {
return nil
}
log, ok := loggerVal.(*Logger)
if ok {
return log
}
panic("cannot cast log value to Logger obj")
} | [
"func",
"(",
"lr",
"*",
"logRegistry",
")",
"getLoggerFromMapping",
"(",
"logger",
"string",
")",
"*",
"Logger",
"{",
"loggerVal",
",",
"found",
":=",
"lr",
".",
"loggers",
".",
"Load",
"(",
"logger",
")",
"\n",
"if",
"!",
"found",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"log",
",",
"ok",
":=",
"loggerVal",
".",
"(",
"*",
"Logger",
")",
"\n",
"if",
"ok",
"{",
"return",
"log",
"\n",
"}",
"\n",
"panic",
"(",
"\"",
"\"",
")",
"\n\n",
"}"
] | // getLoggerFromMapping returns a logger by its name | [
"getLoggerFromMapping",
"returns",
"a",
"logger",
"by",
"its",
"name"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/registry.go#L228-L239 |
4,725 | ligato/cn-infra | logging/logrus/registry.go | AddHook | func (lr *logRegistry) AddHook(hook logrus.Hook) {
defaultLogger.Infof("adding hook %q to registry", hook)
lr.hooks = append(lr.hooks, hook)
lgs := lr.ListLoggers()
for lg := range lgs {
logger, found := lr.Lookup(lg)
if found {
logger.AddHook(hook)
}
}
} | go | func (lr *logRegistry) AddHook(hook logrus.Hook) {
defaultLogger.Infof("adding hook %q to registry", hook)
lr.hooks = append(lr.hooks, hook)
lgs := lr.ListLoggers()
for lg := range lgs {
logger, found := lr.Lookup(lg)
if found {
logger.AddHook(hook)
}
}
} | [
"func",
"(",
"lr",
"*",
"logRegistry",
")",
"AddHook",
"(",
"hook",
"logrus",
".",
"Hook",
")",
"{",
"defaultLogger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"hook",
")",
"\n",
"lr",
".",
"hooks",
"=",
"append",
"(",
"lr",
".",
"hooks",
",",
"hook",
")",
"\n\n",
"lgs",
":=",
"lr",
".",
"ListLoggers",
"(",
")",
"\n",
"for",
"lg",
":=",
"range",
"lgs",
"{",
"logger",
",",
"found",
":=",
"lr",
".",
"Lookup",
"(",
"lg",
")",
"\n",
"if",
"found",
"{",
"logger",
".",
"AddHook",
"(",
"hook",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // HookConfigs stores hook configs provided by log manager
// and applies hook to existing loggers | [
"HookConfigs",
"stores",
"hook",
"configs",
"provided",
"by",
"log",
"manager",
"and",
"applies",
"hook",
"to",
"existing",
"loggers"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/registry.go#L243-L254 |
4,726 | ligato/cn-infra | db/keyval/filedb/plugin.go | Init | func (p *Plugin) Init() error {
// Read fileDB configuration file
var err error
p.config, err = p.getFileDBConfig()
if err != nil || p.disabled {
return err
}
// Register decoders
decoders := []decoder.API{decoder.NewJSONDecoder(), decoder.NewYAMLDecoder()}
if p.client, err = NewClient(p.config.ConfigPaths, p.config.StatusPath, decoders, filesystem.NewFsHandler(), p.Log); err != nil {
return err
}
p.protoWrapper = kvproto.NewProtoWrapper(p.client, &keyval.SerializerJSON{})
return nil
} | go | func (p *Plugin) Init() error {
// Read fileDB configuration file
var err error
p.config, err = p.getFileDBConfig()
if err != nil || p.disabled {
return err
}
// Register decoders
decoders := []decoder.API{decoder.NewJSONDecoder(), decoder.NewYAMLDecoder()}
if p.client, err = NewClient(p.config.ConfigPaths, p.config.StatusPath, decoders, filesystem.NewFsHandler(), p.Log); err != nil {
return err
}
p.protoWrapper = kvproto.NewProtoWrapper(p.client, &keyval.SerializerJSON{})
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Init",
"(",
")",
"error",
"{",
"// Read fileDB configuration file",
"var",
"err",
"error",
"\n",
"p",
".",
"config",
",",
"err",
"=",
"p",
".",
"getFileDBConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"p",
".",
"disabled",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Register decoders",
"decoders",
":=",
"[",
"]",
"decoder",
".",
"API",
"{",
"decoder",
".",
"NewJSONDecoder",
"(",
")",
",",
"decoder",
".",
"NewYAMLDecoder",
"(",
")",
"}",
"\n",
"if",
"p",
".",
"client",
",",
"err",
"=",
"NewClient",
"(",
"p",
".",
"config",
".",
"ConfigPaths",
",",
"p",
".",
"config",
".",
"StatusPath",
",",
"decoders",
",",
"filesystem",
".",
"NewFsHandler",
"(",
")",
",",
"p",
".",
"Log",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"p",
".",
"protoWrapper",
"=",
"kvproto",
".",
"NewProtoWrapper",
"(",
"p",
".",
"client",
",",
"&",
"keyval",
".",
"SerializerJSON",
"{",
"}",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Init reads file config and creates new client to communicate with file system | [
"Init",
"reads",
"file",
"config",
"and",
"creates",
"new",
"client",
"to",
"communicate",
"with",
"file",
"system"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/plugin.go#L53-L70 |
4,727 | ligato/cn-infra | db/keyval/filedb/plugin.go | AfterInit | func (p *Plugin) AfterInit() error {
if !p.disabled {
p.client.eventWatcher()
}
return nil
} | go | func (p *Plugin) AfterInit() error {
if !p.disabled {
p.client.eventWatcher()
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"AfterInit",
"(",
")",
"error",
"{",
"if",
"!",
"p",
".",
"disabled",
"{",
"p",
".",
"client",
".",
"eventWatcher",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // AfterInit starts file system event watcher | [
"AfterInit",
"starts",
"file",
"system",
"event",
"watcher"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/plugin.go#L73-L79 |
4,728 | ligato/cn-infra | datasync/syncbase/change.go | NewChange | func NewChange(key string, value proto.Message, rev int64, changeType datasync.Op) *Change {
return &Change{
changeType: changeType,
KeyVal: &KeyVal{key, &lazyProto{value}, rev},
}
} | go | func NewChange(key string, value proto.Message, rev int64, changeType datasync.Op) *Change {
return &Change{
changeType: changeType,
KeyVal: &KeyVal{key, &lazyProto{value}, rev},
}
} | [
"func",
"NewChange",
"(",
"key",
"string",
",",
"value",
"proto",
".",
"Message",
",",
"rev",
"int64",
",",
"changeType",
"datasync",
".",
"Op",
")",
"*",
"Change",
"{",
"return",
"&",
"Change",
"{",
"changeType",
":",
"changeType",
",",
"KeyVal",
":",
"&",
"KeyVal",
"{",
"key",
",",
"&",
"lazyProto",
"{",
"value",
"}",
",",
"rev",
"}",
",",
"}",
"\n",
"}"
] | // NewChange creates a new instance of Change. | [
"NewChange",
"creates",
"a",
"new",
"instance",
"of",
"Change",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/change.go#L29-L34 |
4,729 | ligato/cn-infra | datasync/syncbase/change.go | NewChangeBytes | func NewChangeBytes(key string, value []byte, rev int64, changeType datasync.Op) *Change {
return &Change{
changeType: changeType,
KeyVal: &KeyValBytes{key, value, rev},
}
} | go | func NewChangeBytes(key string, value []byte, rev int64, changeType datasync.Op) *Change {
return &Change{
changeType: changeType,
KeyVal: &KeyValBytes{key, value, rev},
}
} | [
"func",
"NewChangeBytes",
"(",
"key",
"string",
",",
"value",
"[",
"]",
"byte",
",",
"rev",
"int64",
",",
"changeType",
"datasync",
".",
"Op",
")",
"*",
"Change",
"{",
"return",
"&",
"Change",
"{",
"changeType",
":",
"changeType",
",",
"KeyVal",
":",
"&",
"KeyValBytes",
"{",
"key",
",",
"value",
",",
"rev",
"}",
",",
"}",
"\n",
"}"
] | // NewChangeBytes creates a new instance of NewChangeBytes. | [
"NewChangeBytes",
"creates",
"a",
"new",
"instance",
"of",
"NewChangeBytes",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/change.go#L37-L42 |
4,730 | ligato/cn-infra | examples/kafka-plugin/post-init-consumer/main.go | Init | func (plugin *ExamplePlugin) Init() (err error) {
// Create a synchronous publisher.
// In the manual mode, every publisher has selected its target partition.
plugin.kafkaSyncPublisher, err = plugin.Kafka.NewSyncPublisherToPartition(connection, topic1, syncMessagePartition)
if err != nil {
return err
}
// Prepare subscription channel. Relevant kafka messages are send to this
// channel so that the watcher can read it.
plugin.subscription = make(chan messaging.ProtoMessage)
plugin.Log.Info("Initialization of the custom plugin for the Kafka example is completed")
// Run the producer.
go plugin.producer()
// Verify results and close the example if successful.
go plugin.closeExample()
return err
} | go | func (plugin *ExamplePlugin) Init() (err error) {
// Create a synchronous publisher.
// In the manual mode, every publisher has selected its target partition.
plugin.kafkaSyncPublisher, err = plugin.Kafka.NewSyncPublisherToPartition(connection, topic1, syncMessagePartition)
if err != nil {
return err
}
// Prepare subscription channel. Relevant kafka messages are send to this
// channel so that the watcher can read it.
plugin.subscription = make(chan messaging.ProtoMessage)
plugin.Log.Info("Initialization of the custom plugin for the Kafka example is completed")
// Run the producer.
go plugin.producer()
// Verify results and close the example if successful.
go plugin.closeExample()
return err
} | [
"func",
"(",
"plugin",
"*",
"ExamplePlugin",
")",
"Init",
"(",
")",
"(",
"err",
"error",
")",
"{",
"// Create a synchronous publisher.",
"// In the manual mode, every publisher has selected its target partition.",
"plugin",
".",
"kafkaSyncPublisher",
",",
"err",
"=",
"plugin",
".",
"Kafka",
".",
"NewSyncPublisherToPartition",
"(",
"connection",
",",
"topic1",
",",
"syncMessagePartition",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Prepare subscription channel. Relevant kafka messages are send to this",
"// channel so that the watcher can read it.",
"plugin",
".",
"subscription",
"=",
"make",
"(",
"chan",
"messaging",
".",
"ProtoMessage",
")",
"\n\n",
"plugin",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"// Run the producer.",
"go",
"plugin",
".",
"producer",
"(",
")",
"\n\n",
"// Verify results and close the example if successful.",
"go",
"plugin",
".",
"closeExample",
"(",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Init initializes and starts producers | [
"Init",
"initializes",
"and",
"starts",
"producers"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/kafka-plugin/post-init-consumer/main.go#L87-L108 |
4,731 | ligato/cn-infra | db/keyval/redis/plugin_impl_redis.go | Init | func (p *Plugin) Init() (err error) {
redisCfg, err := p.getRedisConfig()
if err != nil || p.disabled {
return err
}
// Create client according to config
client, err := ConfigToClient(redisCfg)
if err != nil {
return err
}
// Uses config file to establish connection with the database
p.connection, err = NewBytesConnection(client, p.Log)
if err != nil {
return err
}
p.protoWrapper = kvproto.NewProtoWrapper(p.connection, &keyval.SerializerJSON{})
return nil
} | go | func (p *Plugin) Init() (err error) {
redisCfg, err := p.getRedisConfig()
if err != nil || p.disabled {
return err
}
// Create client according to config
client, err := ConfigToClient(redisCfg)
if err != nil {
return err
}
// Uses config file to establish connection with the database
p.connection, err = NewBytesConnection(client, p.Log)
if err != nil {
return err
}
p.protoWrapper = kvproto.NewProtoWrapper(p.connection, &keyval.SerializerJSON{})
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Init",
"(",
")",
"(",
"err",
"error",
")",
"{",
"redisCfg",
",",
"err",
":=",
"p",
".",
"getRedisConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"p",
".",
"disabled",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Create client according to config",
"client",
",",
"err",
":=",
"ConfigToClient",
"(",
"redisCfg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Uses config file to establish connection with the database",
"p",
".",
"connection",
",",
"err",
"=",
"NewBytesConnection",
"(",
"client",
",",
"p",
".",
"Log",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
".",
"protoWrapper",
"=",
"kvproto",
".",
"NewProtoWrapper",
"(",
"p",
".",
"connection",
",",
"&",
"keyval",
".",
"SerializerJSON",
"{",
"}",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Init retrieves redis configuration and establishes a new connection
// with the redis data store.
// If the configuration file doesn't exist or cannot be read, the returned errora
// will be of os.PathError type. An untyped error is returned in case the file
// doesn't contain a valid YAML configuration. | [
"Init",
"retrieves",
"redis",
"configuration",
"and",
"establishes",
"a",
"new",
"connection",
"with",
"the",
"redis",
"data",
"store",
".",
"If",
"the",
"configuration",
"file",
"doesn",
"t",
"exist",
"or",
"cannot",
"be",
"read",
"the",
"returned",
"errora",
"will",
"be",
"of",
"os",
".",
"PathError",
"type",
".",
"An",
"untyped",
"error",
"is",
"returned",
"in",
"case",
"the",
"file",
"doesn",
"t",
"contain",
"a",
"valid",
"YAML",
"configuration",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/redis/plugin_impl_redis.go#L54-L74 |
4,732 | ligato/cn-infra | db/keyval/redis/plugin_impl_redis.go | AfterInit | func (p *Plugin) AfterInit() error {
if p.StatusCheck != nil && !p.disabled {
p.StatusCheck.Register(p.PluginName, func() (statuscheck.PluginState, error) {
_, _, err := p.NewBroker("/").GetValue(healthCheckProbeKey, nil)
if err == nil {
return statuscheck.OK, nil
}
return statuscheck.Error, err
})
p.Log.Infof("Status check for %s was started", p.PluginName)
}
return nil
} | go | func (p *Plugin) AfterInit() error {
if p.StatusCheck != nil && !p.disabled {
p.StatusCheck.Register(p.PluginName, func() (statuscheck.PluginState, error) {
_, _, err := p.NewBroker("/").GetValue(healthCheckProbeKey, nil)
if err == nil {
return statuscheck.OK, nil
}
return statuscheck.Error, err
})
p.Log.Infof("Status check for %s was started", p.PluginName)
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"AfterInit",
"(",
")",
"error",
"{",
"if",
"p",
".",
"StatusCheck",
"!=",
"nil",
"&&",
"!",
"p",
".",
"disabled",
"{",
"p",
".",
"StatusCheck",
".",
"Register",
"(",
"p",
".",
"PluginName",
",",
"func",
"(",
")",
"(",
"statuscheck",
".",
"PluginState",
",",
"error",
")",
"{",
"_",
",",
"_",
",",
"err",
":=",
"p",
".",
"NewBroker",
"(",
"\"",
"\"",
")",
".",
"GetValue",
"(",
"healthCheckProbeKey",
",",
"nil",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"statuscheck",
".",
"OK",
",",
"nil",
"\n",
"}",
"\n",
"return",
"statuscheck",
".",
"Error",
",",
"err",
"\n",
"}",
")",
"\n",
"p",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"p",
".",
"PluginName",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // AfterInit registers redis to status check if required | [
"AfterInit",
"registers",
"redis",
"to",
"status",
"check",
"if",
"required"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/redis/plugin_impl_redis.go#L77-L90 |
4,733 | ligato/cn-infra | db/keyval/consul/plugin.go | Init | func (p *Plugin) Init() (err error) {
if p.Config == nil {
p.Config, err = p.getConfig()
if err != nil || p.disabled {
return err
}
}
clientCfg, err := ConfigToClient(p.Config)
if err != nil {
return err
}
p.client, err = NewClient(clientCfg)
if err != nil {
p.Log.Errorf("Err: %v", err)
return err
}
p.reconnectResync = p.Config.ReconnectResync
p.protoWrapper = kvproto.NewProtoWrapper(p.client, &keyval.SerializerJSON{})
// Register for providing status reports (polling mode)
if p.StatusCheck != nil {
p.StatusCheck.Register(p.PluginName, p.statusCheckProbe)
} else {
p.Log.Warnf("Unable to start status check for consul")
}
return nil
} | go | func (p *Plugin) Init() (err error) {
if p.Config == nil {
p.Config, err = p.getConfig()
if err != nil || p.disabled {
return err
}
}
clientCfg, err := ConfigToClient(p.Config)
if err != nil {
return err
}
p.client, err = NewClient(clientCfg)
if err != nil {
p.Log.Errorf("Err: %v", err)
return err
}
p.reconnectResync = p.Config.ReconnectResync
p.protoWrapper = kvproto.NewProtoWrapper(p.client, &keyval.SerializerJSON{})
// Register for providing status reports (polling mode)
if p.StatusCheck != nil {
p.StatusCheck.Register(p.PluginName, p.statusCheckProbe)
} else {
p.Log.Warnf("Unable to start status check for consul")
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Init",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"p",
".",
"Config",
"==",
"nil",
"{",
"p",
".",
"Config",
",",
"err",
"=",
"p",
".",
"getConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"p",
".",
"disabled",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"clientCfg",
",",
"err",
":=",
"ConfigToClient",
"(",
"p",
".",
"Config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
".",
"client",
",",
"err",
"=",
"NewClient",
"(",
"clientCfg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"p",
".",
"reconnectResync",
"=",
"p",
".",
"Config",
".",
"ReconnectResync",
"\n",
"p",
".",
"protoWrapper",
"=",
"kvproto",
".",
"NewProtoWrapper",
"(",
"p",
".",
"client",
",",
"&",
"keyval",
".",
"SerializerJSON",
"{",
"}",
")",
"\n\n",
"// Register for providing status reports (polling mode)",
"if",
"p",
".",
"StatusCheck",
"!=",
"nil",
"{",
"p",
".",
"StatusCheck",
".",
"Register",
"(",
"p",
".",
"PluginName",
",",
"p",
".",
"statusCheckProbe",
")",
"\n",
"}",
"else",
"{",
"p",
".",
"Log",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Init initializes Consul plugin. | [
"Init",
"initializes",
"Consul",
"plugin",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/consul/plugin.go#L62-L91 |
4,734 | ligato/cn-infra | db/keyval/consul/plugin.go | ConfigToClient | func ConfigToClient(cfg *Config) (*api.Config, error) {
clientCfg := api.DefaultConfig()
if cfg.Address != "" {
clientCfg.Address = cfg.Address
}
return clientCfg, nil
} | go | func ConfigToClient(cfg *Config) (*api.Config, error) {
clientCfg := api.DefaultConfig()
if cfg.Address != "" {
clientCfg.Address = cfg.Address
}
return clientCfg, nil
} | [
"func",
"ConfigToClient",
"(",
"cfg",
"*",
"Config",
")",
"(",
"*",
"api",
".",
"Config",
",",
"error",
")",
"{",
"clientCfg",
":=",
"api",
".",
"DefaultConfig",
"(",
")",
"\n",
"if",
"cfg",
".",
"Address",
"!=",
"\"",
"\"",
"{",
"clientCfg",
".",
"Address",
"=",
"cfg",
".",
"Address",
"\n",
"}",
"\n",
"return",
"clientCfg",
",",
"nil",
"\n",
"}"
] | // ConfigToClient transforms Config into api.Config,
// which is ready for use with underlying consul package. | [
"ConfigToClient",
"transforms",
"Config",
"into",
"api",
".",
"Config",
"which",
"is",
"ready",
"for",
"use",
"with",
"underlying",
"consul",
"package",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/consul/plugin.go#L146-L152 |
4,735 | ligato/cn-infra | idxmap/chan.go | ToChan | func ToChan(ch chan NamedMappingGenericEvent, opts ...interface{}) func(dto NamedMappingGenericEvent) {
timeout := DefaultNotifTimeout
var logger logging.Logger = logrus.DefaultLogger()
/*for _, opt := range opts {
switch opt.(type) {
case *core.WithLoggerOpt:
logger = opt.(*core.WithLoggerOpt).Logger
case *core.WithTimeoutOpt:
timeout = opt.(*core.WithTimeoutOpt).Timeout
}
}*/
return func(dto NamedMappingGenericEvent) {
select {
case ch <- dto:
case <-time.After(timeout):
logger.Warn("Unable to deliver notification")
}
}
} | go | func ToChan(ch chan NamedMappingGenericEvent, opts ...interface{}) func(dto NamedMappingGenericEvent) {
timeout := DefaultNotifTimeout
var logger logging.Logger = logrus.DefaultLogger()
/*for _, opt := range opts {
switch opt.(type) {
case *core.WithLoggerOpt:
logger = opt.(*core.WithLoggerOpt).Logger
case *core.WithTimeoutOpt:
timeout = opt.(*core.WithTimeoutOpt).Timeout
}
}*/
return func(dto NamedMappingGenericEvent) {
select {
case ch <- dto:
case <-time.After(timeout):
logger.Warn("Unable to deliver notification")
}
}
} | [
"func",
"ToChan",
"(",
"ch",
"chan",
"NamedMappingGenericEvent",
",",
"opts",
"...",
"interface",
"{",
"}",
")",
"func",
"(",
"dto",
"NamedMappingGenericEvent",
")",
"{",
"timeout",
":=",
"DefaultNotifTimeout",
"\n",
"var",
"logger",
"logging",
".",
"Logger",
"=",
"logrus",
".",
"DefaultLogger",
"(",
")",
"\n\n",
"/*for _, opt := range opts {\n\t\tswitch opt.(type) {\n\t\tcase *core.WithLoggerOpt:\n\t\t\tlogger = opt.(*core.WithLoggerOpt).Logger\n\t\tcase *core.WithTimeoutOpt:\n\t\t\ttimeout = opt.(*core.WithTimeoutOpt).Timeout\n\t\t}\n\t}*/",
"return",
"func",
"(",
"dto",
"NamedMappingGenericEvent",
")",
"{",
"select",
"{",
"case",
"ch",
"<-",
"dto",
":",
"case",
"<-",
"time",
".",
"After",
"(",
"timeout",
")",
":",
"logger",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // ToChan creates a callback that can be passed to the Watch function
// in order to receive notifications through a channel. If the notification
// can not be delivered until timeout, it is dropped. | [
"ToChan",
"creates",
"a",
"callback",
"that",
"can",
"be",
"passed",
"to",
"the",
"Watch",
"function",
"in",
"order",
"to",
"receive",
"notifications",
"through",
"a",
"channel",
".",
"If",
"the",
"notification",
"can",
"not",
"be",
"delivered",
"until",
"timeout",
"it",
"is",
"dropped",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/idxmap/chan.go#L30-L51 |
4,736 | ligato/cn-infra | examples/tutorials/02_plugin-deps/main.go | NewHelloWorld | func NewHelloWorld() *HelloWorld {
// Create new instance.
p := new(HelloWorld)
// Set the plugin name.
p.SetName("helloworld")
// Initialize essential plugin deps: logger and config.
p.Setup()
return p
} | go | func NewHelloWorld() *HelloWorld {
// Create new instance.
p := new(HelloWorld)
// Set the plugin name.
p.SetName("helloworld")
// Initialize essential plugin deps: logger and config.
p.Setup()
return p
} | [
"func",
"NewHelloWorld",
"(",
")",
"*",
"HelloWorld",
"{",
"// Create new instance.",
"p",
":=",
"new",
"(",
"HelloWorld",
")",
"\n",
"// Set the plugin name.",
"p",
".",
"SetName",
"(",
"\"",
"\"",
")",
"\n",
"// Initialize essential plugin deps: logger and config.",
"p",
".",
"Setup",
"(",
")",
"\n",
"return",
"p",
"\n",
"}"
] | // NewHelloWorld is a constructor for our HelloWorld plugin. | [
"NewHelloWorld",
"is",
"a",
"constructor",
"for",
"our",
"HelloWorld",
"plugin",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/tutorials/02_plugin-deps/main.go#L44-L52 |
4,737 | ligato/cn-infra | messaging/kafka/mux/multiplexer.go | NewMultiplexer | func NewMultiplexer(consumerFactory ConsumerFactory, producers multiplexerProducers, clientCfg *client.Config,
name string, log logging.Logger) *Multiplexer {
if clientCfg.Logger == nil {
clientCfg.Logger = log
}
cl := &Multiplexer{consumerFactory: consumerFactory,
Logger: log,
name: name,
mapping: []*consumerSubscription{},
multiplexerProducers: producers,
config: clientCfg,
}
go cl.watchAsyncProducerChannels()
if producers.manAsyncProducer != nil && producers.manAsyncProducer.Config != nil {
go cl.watchManualAsyncProducerChannels()
}
return cl
} | go | func NewMultiplexer(consumerFactory ConsumerFactory, producers multiplexerProducers, clientCfg *client.Config,
name string, log logging.Logger) *Multiplexer {
if clientCfg.Logger == nil {
clientCfg.Logger = log
}
cl := &Multiplexer{consumerFactory: consumerFactory,
Logger: log,
name: name,
mapping: []*consumerSubscription{},
multiplexerProducers: producers,
config: clientCfg,
}
go cl.watchAsyncProducerChannels()
if producers.manAsyncProducer != nil && producers.manAsyncProducer.Config != nil {
go cl.watchManualAsyncProducerChannels()
}
return cl
} | [
"func",
"NewMultiplexer",
"(",
"consumerFactory",
"ConsumerFactory",
",",
"producers",
"multiplexerProducers",
",",
"clientCfg",
"*",
"client",
".",
"Config",
",",
"name",
"string",
",",
"log",
"logging",
".",
"Logger",
")",
"*",
"Multiplexer",
"{",
"if",
"clientCfg",
".",
"Logger",
"==",
"nil",
"{",
"clientCfg",
".",
"Logger",
"=",
"log",
"\n",
"}",
"\n",
"cl",
":=",
"&",
"Multiplexer",
"{",
"consumerFactory",
":",
"consumerFactory",
",",
"Logger",
":",
"log",
",",
"name",
":",
"name",
",",
"mapping",
":",
"[",
"]",
"*",
"consumerSubscription",
"{",
"}",
",",
"multiplexerProducers",
":",
"producers",
",",
"config",
":",
"clientCfg",
",",
"}",
"\n\n",
"go",
"cl",
".",
"watchAsyncProducerChannels",
"(",
")",
"\n",
"if",
"producers",
".",
"manAsyncProducer",
"!=",
"nil",
"&&",
"producers",
".",
"manAsyncProducer",
".",
"Config",
"!=",
"nil",
"{",
"go",
"cl",
".",
"watchManualAsyncProducerChannels",
"(",
")",
"\n",
"}",
"\n",
"return",
"cl",
"\n",
"}"
] | // NewMultiplexer creates new instance of Kafka Multiplexer | [
"NewMultiplexer",
"creates",
"new",
"instance",
"of",
"Kafka",
"Multiplexer"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/multiplexer.go#L92-L110 |
4,738 | ligato/cn-infra | messaging/kafka/mux/multiplexer.go | Start | func (mux *Multiplexer) Start() error {
mux.rwlock.Lock()
defer mux.rwlock.Unlock()
var err error
if mux.started {
return fmt.Errorf("multiplexer has been started already")
}
// block further Consumer consumers
mux.started = true
var hashTopics, manTopics []string
for _, subscription := range mux.mapping {
if subscription.manual {
manTopics = append(manTopics, subscription.topic)
continue
}
hashTopics = append(hashTopics, subscription.topic)
}
mux.config.SetRecvMessageChan(make(chan *client.ConsumerMessage))
mux.config.GroupID = mux.name
mux.config.SetInitialOffset(sarama.OffsetOldest)
mux.config.Topics = append(hashTopics, manTopics...)
// create consumer
mux.WithFields(logging.Fields{"hashTopics": hashTopics, "manualTopics": manTopics}).Debugf("Consuming started")
mux.Consumer, err = client.NewConsumer(mux.config, nil)
if err != nil {
return err
}
if len(hashTopics) == 0 {
mux.Debug("No topics for hash partitioner")
} else {
mux.WithFields(logging.Fields{"topics": hashTopics}).Debugf("Consuming (hash) started")
mux.Consumer.StartConsumerHandlers()
}
if len(manTopics) == 0 {
mux.Debug("No topics for manual partitioner")
} else {
mux.WithFields(logging.Fields{"topics": manTopics}).Debugf("Consuming (manual) started")
for _, sub := range mux.mapping {
if sub.manual {
sConsumer := mux.Consumer.SConsumer
if sConsumer == nil {
return fmt.Errorf("consumer for manual partition is not available")
}
partitionConsumer, err := sConsumer.ConsumePartition(sub.topic, sub.partition, sub.offset)
if err != nil {
return err
}
// Store partition consumer in subscription so it can be closed lately
sub.partitionConsumer = &partitionConsumer
mux.Logger.WithFields(logging.Fields{"topic": sub.topic, "partition": sub.partition, "offset": sub.offset}).Info("Partition sConsumer started")
mux.Consumer.StartConsumerManualHandlers(partitionConsumer)
}
}
}
go mux.genericConsumer()
go mux.manualConsumer(mux.Consumer)
return err
} | go | func (mux *Multiplexer) Start() error {
mux.rwlock.Lock()
defer mux.rwlock.Unlock()
var err error
if mux.started {
return fmt.Errorf("multiplexer has been started already")
}
// block further Consumer consumers
mux.started = true
var hashTopics, manTopics []string
for _, subscription := range mux.mapping {
if subscription.manual {
manTopics = append(manTopics, subscription.topic)
continue
}
hashTopics = append(hashTopics, subscription.topic)
}
mux.config.SetRecvMessageChan(make(chan *client.ConsumerMessage))
mux.config.GroupID = mux.name
mux.config.SetInitialOffset(sarama.OffsetOldest)
mux.config.Topics = append(hashTopics, manTopics...)
// create consumer
mux.WithFields(logging.Fields{"hashTopics": hashTopics, "manualTopics": manTopics}).Debugf("Consuming started")
mux.Consumer, err = client.NewConsumer(mux.config, nil)
if err != nil {
return err
}
if len(hashTopics) == 0 {
mux.Debug("No topics for hash partitioner")
} else {
mux.WithFields(logging.Fields{"topics": hashTopics}).Debugf("Consuming (hash) started")
mux.Consumer.StartConsumerHandlers()
}
if len(manTopics) == 0 {
mux.Debug("No topics for manual partitioner")
} else {
mux.WithFields(logging.Fields{"topics": manTopics}).Debugf("Consuming (manual) started")
for _, sub := range mux.mapping {
if sub.manual {
sConsumer := mux.Consumer.SConsumer
if sConsumer == nil {
return fmt.Errorf("consumer for manual partition is not available")
}
partitionConsumer, err := sConsumer.ConsumePartition(sub.topic, sub.partition, sub.offset)
if err != nil {
return err
}
// Store partition consumer in subscription so it can be closed lately
sub.partitionConsumer = &partitionConsumer
mux.Logger.WithFields(logging.Fields{"topic": sub.topic, "partition": sub.partition, "offset": sub.offset}).Info("Partition sConsumer started")
mux.Consumer.StartConsumerManualHandlers(partitionConsumer)
}
}
}
go mux.genericConsumer()
go mux.manualConsumer(mux.Consumer)
return err
} | [
"func",
"(",
"mux",
"*",
"Multiplexer",
")",
"Start",
"(",
")",
"error",
"{",
"mux",
".",
"rwlock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mux",
".",
"rwlock",
".",
"Unlock",
"(",
")",
"\n",
"var",
"err",
"error",
"\n\n",
"if",
"mux",
".",
"started",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// block further Consumer consumers",
"mux",
".",
"started",
"=",
"true",
"\n\n",
"var",
"hashTopics",
",",
"manTopics",
"[",
"]",
"string",
"\n\n",
"for",
"_",
",",
"subscription",
":=",
"range",
"mux",
".",
"mapping",
"{",
"if",
"subscription",
".",
"manual",
"{",
"manTopics",
"=",
"append",
"(",
"manTopics",
",",
"subscription",
".",
"topic",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"hashTopics",
"=",
"append",
"(",
"hashTopics",
",",
"subscription",
".",
"topic",
")",
"\n",
"}",
"\n\n",
"mux",
".",
"config",
".",
"SetRecvMessageChan",
"(",
"make",
"(",
"chan",
"*",
"client",
".",
"ConsumerMessage",
")",
")",
"\n",
"mux",
".",
"config",
".",
"GroupID",
"=",
"mux",
".",
"name",
"\n",
"mux",
".",
"config",
".",
"SetInitialOffset",
"(",
"sarama",
".",
"OffsetOldest",
")",
"\n",
"mux",
".",
"config",
".",
"Topics",
"=",
"append",
"(",
"hashTopics",
",",
"manTopics",
"...",
")",
"\n\n",
"// create consumer",
"mux",
".",
"WithFields",
"(",
"logging",
".",
"Fields",
"{",
"\"",
"\"",
":",
"hashTopics",
",",
"\"",
"\"",
":",
"manTopics",
"}",
")",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"mux",
".",
"Consumer",
",",
"err",
"=",
"client",
".",
"NewConsumer",
"(",
"mux",
".",
"config",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"hashTopics",
")",
"==",
"0",
"{",
"mux",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"mux",
".",
"WithFields",
"(",
"logging",
".",
"Fields",
"{",
"\"",
"\"",
":",
"hashTopics",
"}",
")",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"mux",
".",
"Consumer",
".",
"StartConsumerHandlers",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"manTopics",
")",
"==",
"0",
"{",
"mux",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"mux",
".",
"WithFields",
"(",
"logging",
".",
"Fields",
"{",
"\"",
"\"",
":",
"manTopics",
"}",
")",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"sub",
":=",
"range",
"mux",
".",
"mapping",
"{",
"if",
"sub",
".",
"manual",
"{",
"sConsumer",
":=",
"mux",
".",
"Consumer",
".",
"SConsumer",
"\n",
"if",
"sConsumer",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"partitionConsumer",
",",
"err",
":=",
"sConsumer",
".",
"ConsumePartition",
"(",
"sub",
".",
"topic",
",",
"sub",
".",
"partition",
",",
"sub",
".",
"offset",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Store partition consumer in subscription so it can be closed lately",
"sub",
".",
"partitionConsumer",
"=",
"&",
"partitionConsumer",
"\n",
"mux",
".",
"Logger",
".",
"WithFields",
"(",
"logging",
".",
"Fields",
"{",
"\"",
"\"",
":",
"sub",
".",
"topic",
",",
"\"",
"\"",
":",
"sub",
".",
"partition",
",",
"\"",
"\"",
":",
"sub",
".",
"offset",
"}",
")",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"mux",
".",
"Consumer",
".",
"StartConsumerManualHandlers",
"(",
"partitionConsumer",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"go",
"mux",
".",
"genericConsumer",
"(",
")",
"\n",
"go",
"mux",
".",
"manualConsumer",
"(",
"mux",
".",
"Consumer",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Start should be called once all the Connections have been subscribed
// for topic consumption. An attempt to start consuming a topic after the multiplexer is started
// returns an error. | [
"Start",
"should",
"be",
"called",
"once",
"all",
"the",
"Connections",
"have",
"been",
"subscribed",
"for",
"topic",
"consumption",
".",
"An",
"attempt",
"to",
"start",
"consuming",
"a",
"topic",
"after",
"the",
"multiplexer",
"is",
"started",
"returns",
"an",
"error",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/multiplexer.go#L162-L230 |
4,739 | ligato/cn-infra | messaging/kafka/mux/multiplexer.go | Close | func (mux *Multiplexer) Close() {
safeclose.Close(
mux.Consumer,
mux.hashSyncProducer,
mux.hashAsyncProducer,
mux.manSyncProducer,
mux.manAsyncProducer)
} | go | func (mux *Multiplexer) Close() {
safeclose.Close(
mux.Consumer,
mux.hashSyncProducer,
mux.hashAsyncProducer,
mux.manSyncProducer,
mux.manAsyncProducer)
} | [
"func",
"(",
"mux",
"*",
"Multiplexer",
")",
"Close",
"(",
")",
"{",
"safeclose",
".",
"Close",
"(",
"mux",
".",
"Consumer",
",",
"mux",
".",
"hashSyncProducer",
",",
"mux",
".",
"hashAsyncProducer",
",",
"mux",
".",
"manSyncProducer",
",",
"mux",
".",
"manAsyncProducer",
")",
"\n",
"}"
] | // Close cleans up the resources used by the Multiplexer | [
"Close",
"cleans",
"up",
"the",
"resources",
"used",
"by",
"the",
"Multiplexer"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/multiplexer.go#L233-L240 |
4,740 | ligato/cn-infra | messaging/kafka/mux/multiplexer.go | NewBytesConnection | func (mux *Multiplexer) NewBytesConnection(name string) *BytesConnectionStr {
return &BytesConnectionStr{BytesConnectionFields{multiplexer: mux, name: name}}
} | go | func (mux *Multiplexer) NewBytesConnection(name string) *BytesConnectionStr {
return &BytesConnectionStr{BytesConnectionFields{multiplexer: mux, name: name}}
} | [
"func",
"(",
"mux",
"*",
"Multiplexer",
")",
"NewBytesConnection",
"(",
"name",
"string",
")",
"*",
"BytesConnectionStr",
"{",
"return",
"&",
"BytesConnectionStr",
"{",
"BytesConnectionFields",
"{",
"multiplexer",
":",
"mux",
",",
"name",
":",
"name",
"}",
"}",
"\n",
"}"
] | // NewBytesConnection creates instance of the BytesConnectionStr that provides access to shared
// Multiplexer's clients with hash partitioner. | [
"NewBytesConnection",
"creates",
"instance",
"of",
"the",
"BytesConnectionStr",
"that",
"provides",
"access",
"to",
"shared",
"Multiplexer",
"s",
"clients",
"with",
"hash",
"partitioner",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/multiplexer.go#L244-L246 |
4,741 | ligato/cn-infra | messaging/kafka/mux/multiplexer.go | NewBytesManualConnection | func (mux *Multiplexer) NewBytesManualConnection(name string) *BytesManualConnectionStr {
return &BytesManualConnectionStr{BytesConnectionFields{multiplexer: mux, name: name}}
} | go | func (mux *Multiplexer) NewBytesManualConnection(name string) *BytesManualConnectionStr {
return &BytesManualConnectionStr{BytesConnectionFields{multiplexer: mux, name: name}}
} | [
"func",
"(",
"mux",
"*",
"Multiplexer",
")",
"NewBytesManualConnection",
"(",
"name",
"string",
")",
"*",
"BytesManualConnectionStr",
"{",
"return",
"&",
"BytesManualConnectionStr",
"{",
"BytesConnectionFields",
"{",
"multiplexer",
":",
"mux",
",",
"name",
":",
"name",
"}",
"}",
"\n",
"}"
] | // NewBytesManualConnection creates instance of the BytesManualConnectionStr that provides access to shared
// Multiplexer's clients with manual partitioner. | [
"NewBytesManualConnection",
"creates",
"instance",
"of",
"the",
"BytesManualConnectionStr",
"that",
"provides",
"access",
"to",
"shared",
"Multiplexer",
"s",
"clients",
"with",
"manual",
"partitioner",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/multiplexer.go#L250-L252 |
4,742 | ligato/cn-infra | messaging/kafka/mux/multiplexer.go | NewProtoConnection | func (mux *Multiplexer) NewProtoConnection(name string, serializer keyval.Serializer) *ProtoConnection {
return &ProtoConnection{ProtoConnectionFields{multiplexer: mux, serializer: serializer, name: name}}
} | go | func (mux *Multiplexer) NewProtoConnection(name string, serializer keyval.Serializer) *ProtoConnection {
return &ProtoConnection{ProtoConnectionFields{multiplexer: mux, serializer: serializer, name: name}}
} | [
"func",
"(",
"mux",
"*",
"Multiplexer",
")",
"NewProtoConnection",
"(",
"name",
"string",
",",
"serializer",
"keyval",
".",
"Serializer",
")",
"*",
"ProtoConnection",
"{",
"return",
"&",
"ProtoConnection",
"{",
"ProtoConnectionFields",
"{",
"multiplexer",
":",
"mux",
",",
"serializer",
":",
"serializer",
",",
"name",
":",
"name",
"}",
"}",
"\n",
"}"
] | // NewProtoConnection creates instance of the ProtoConnection that provides access to shared
// Multiplexer's clients with hash partitioner. | [
"NewProtoConnection",
"creates",
"instance",
"of",
"the",
"ProtoConnection",
"that",
"provides",
"access",
"to",
"shared",
"Multiplexer",
"s",
"clients",
"with",
"hash",
"partitioner",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/multiplexer.go#L256-L258 |
4,743 | ligato/cn-infra | messaging/kafka/mux/multiplexer.go | NewProtoManualConnection | func (mux *Multiplexer) NewProtoManualConnection(name string, serializer keyval.Serializer) *ProtoManualConnection {
return &ProtoManualConnection{ProtoConnectionFields{multiplexer: mux, serializer: serializer, name: name}}
} | go | func (mux *Multiplexer) NewProtoManualConnection(name string, serializer keyval.Serializer) *ProtoManualConnection {
return &ProtoManualConnection{ProtoConnectionFields{multiplexer: mux, serializer: serializer, name: name}}
} | [
"func",
"(",
"mux",
"*",
"Multiplexer",
")",
"NewProtoManualConnection",
"(",
"name",
"string",
",",
"serializer",
"keyval",
".",
"Serializer",
")",
"*",
"ProtoManualConnection",
"{",
"return",
"&",
"ProtoManualConnection",
"{",
"ProtoConnectionFields",
"{",
"multiplexer",
":",
"mux",
",",
"serializer",
":",
"serializer",
",",
"name",
":",
"name",
"}",
"}",
"\n",
"}"
] | // NewProtoManualConnection creates instance of the ProtoConnectionFields that provides access to shared
// Multiplexer's clients with manual partitioner. | [
"NewProtoManualConnection",
"creates",
"instance",
"of",
"the",
"ProtoConnectionFields",
"that",
"provides",
"access",
"to",
"shared",
"Multiplexer",
"s",
"clients",
"with",
"manual",
"partitioner",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/multiplexer.go#L262-L264 |
4,744 | ligato/cn-infra | messaging/kafka/mux/multiplexer.go | propagateMessage | func (mux *Multiplexer) propagateMessage(msg *client.ConsumerMessage) {
mux.rwlock.RLock()
defer mux.rwlock.RUnlock()
if msg == nil {
return
}
// Find subscribed topics. Note: topic can be subscribed for both dynamic and manual consuming
for _, subscription := range mux.mapping {
if msg.Topic == subscription.topic {
// Clustered mode - message is consumed only on right partition and offset
if subscription.manual {
if msg.Partition == subscription.partition && msg.Offset >= subscription.offset {
mux.Debug("offset ", msg.Offset, string(msg.Value), string(msg.Key), msg.Partition)
subscription.byteConsMsg(msg)
}
} else {
// Non-manual mode
// if we are not able to write into the channel we should skip the receiver
// and report an error to avoid deadlock
mux.Debug("offset ", msg.Offset, string(msg.Value), string(msg.Key), msg.Partition)
subscription.byteConsMsg(msg)
}
}
}
} | go | func (mux *Multiplexer) propagateMessage(msg *client.ConsumerMessage) {
mux.rwlock.RLock()
defer mux.rwlock.RUnlock()
if msg == nil {
return
}
// Find subscribed topics. Note: topic can be subscribed for both dynamic and manual consuming
for _, subscription := range mux.mapping {
if msg.Topic == subscription.topic {
// Clustered mode - message is consumed only on right partition and offset
if subscription.manual {
if msg.Partition == subscription.partition && msg.Offset >= subscription.offset {
mux.Debug("offset ", msg.Offset, string(msg.Value), string(msg.Key), msg.Partition)
subscription.byteConsMsg(msg)
}
} else {
// Non-manual mode
// if we are not able to write into the channel we should skip the receiver
// and report an error to avoid deadlock
mux.Debug("offset ", msg.Offset, string(msg.Value), string(msg.Key), msg.Partition)
subscription.byteConsMsg(msg)
}
}
}
} | [
"func",
"(",
"mux",
"*",
"Multiplexer",
")",
"propagateMessage",
"(",
"msg",
"*",
"client",
".",
"ConsumerMessage",
")",
"{",
"mux",
".",
"rwlock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"mux",
".",
"rwlock",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"msg",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Find subscribed topics. Note: topic can be subscribed for both dynamic and manual consuming",
"for",
"_",
",",
"subscription",
":=",
"range",
"mux",
".",
"mapping",
"{",
"if",
"msg",
".",
"Topic",
"==",
"subscription",
".",
"topic",
"{",
"// Clustered mode - message is consumed only on right partition and offset",
"if",
"subscription",
".",
"manual",
"{",
"if",
"msg",
".",
"Partition",
"==",
"subscription",
".",
"partition",
"&&",
"msg",
".",
"Offset",
">=",
"subscription",
".",
"offset",
"{",
"mux",
".",
"Debug",
"(",
"\"",
"\"",
",",
"msg",
".",
"Offset",
",",
"string",
"(",
"msg",
".",
"Value",
")",
",",
"string",
"(",
"msg",
".",
"Key",
")",
",",
"msg",
".",
"Partition",
")",
"\n",
"subscription",
".",
"byteConsMsg",
"(",
"msg",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// Non-manual mode",
"// if we are not able to write into the channel we should skip the receiver",
"// and report an error to avoid deadlock",
"mux",
".",
"Debug",
"(",
"\"",
"\"",
",",
"msg",
".",
"Offset",
",",
"string",
"(",
"msg",
".",
"Value",
")",
",",
"string",
"(",
"msg",
".",
"Key",
")",
",",
"msg",
".",
"Partition",
")",
"\n",
"subscription",
".",
"byteConsMsg",
"(",
"msg",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Propagates incoming messages to respective channels. | [
"Propagates",
"incoming",
"messages",
"to",
"respective",
"channels",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/multiplexer.go#L267-L293 |
4,745 | ligato/cn-infra | messaging/kafka/mux/multiplexer.go | genericConsumer | func (mux *Multiplexer) genericConsumer() {
mux.Debug("Generic Consumer started")
for {
select {
case <-mux.Consumer.GetCloseChannel():
mux.Debug("Closing Consumer")
return
case msg := <-mux.Consumer.Config.RecvMessageChan:
// 'hash' partitioner messages will be marked
mux.propagateMessage(msg)
case err := <-mux.Consumer.Config.RecvErrorChan:
mux.Error("Received partitionConsumer error ", err)
}
}
} | go | func (mux *Multiplexer) genericConsumer() {
mux.Debug("Generic Consumer started")
for {
select {
case <-mux.Consumer.GetCloseChannel():
mux.Debug("Closing Consumer")
return
case msg := <-mux.Consumer.Config.RecvMessageChan:
// 'hash' partitioner messages will be marked
mux.propagateMessage(msg)
case err := <-mux.Consumer.Config.RecvErrorChan:
mux.Error("Received partitionConsumer error ", err)
}
}
} | [
"func",
"(",
"mux",
"*",
"Multiplexer",
")",
"genericConsumer",
"(",
")",
"{",
"mux",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"mux",
".",
"Consumer",
".",
"GetCloseChannel",
"(",
")",
":",
"mux",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"case",
"msg",
":=",
"<-",
"mux",
".",
"Consumer",
".",
"Config",
".",
"RecvMessageChan",
":",
"// 'hash' partitioner messages will be marked",
"mux",
".",
"propagateMessage",
"(",
"msg",
")",
"\n",
"case",
"err",
":=",
"<-",
"mux",
".",
"Consumer",
".",
"Config",
".",
"RecvErrorChan",
":",
"mux",
".",
"Error",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // genericConsumer handles incoming messages to the multiplexer and distributes them among the subscribers. | [
"genericConsumer",
"handles",
"incoming",
"messages",
"to",
"the",
"multiplexer",
"and",
"distributes",
"them",
"among",
"the",
"subscribers",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/multiplexer.go#L296-L310 |
4,746 | ligato/cn-infra | messaging/kafka/mux/multiplexer.go | stopConsuming | func (mux *Multiplexer) stopConsuming(topic string, name string) error {
mux.rwlock.Lock()
defer mux.rwlock.Unlock()
var wasError error
var topicFound bool
for index, subs := range mux.mapping {
if !subs.manual && subs.topic == topic && subs.connectionName == name {
topicFound = true
mux.mapping = append(mux.mapping[:index], mux.mapping[index+1:]...)
}
}
if !topicFound {
wasError = fmt.Errorf("topic %s was not consumed by '%s'", topic, name)
}
return wasError
} | go | func (mux *Multiplexer) stopConsuming(topic string, name string) error {
mux.rwlock.Lock()
defer mux.rwlock.Unlock()
var wasError error
var topicFound bool
for index, subs := range mux.mapping {
if !subs.manual && subs.topic == topic && subs.connectionName == name {
topicFound = true
mux.mapping = append(mux.mapping[:index], mux.mapping[index+1:]...)
}
}
if !topicFound {
wasError = fmt.Errorf("topic %s was not consumed by '%s'", topic, name)
}
return wasError
} | [
"func",
"(",
"mux",
"*",
"Multiplexer",
")",
"stopConsuming",
"(",
"topic",
"string",
",",
"name",
"string",
")",
"error",
"{",
"mux",
".",
"rwlock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"mux",
".",
"rwlock",
".",
"Unlock",
"(",
")",
"\n\n",
"var",
"wasError",
"error",
"\n",
"var",
"topicFound",
"bool",
"\n",
"for",
"index",
",",
"subs",
":=",
"range",
"mux",
".",
"mapping",
"{",
"if",
"!",
"subs",
".",
"manual",
"&&",
"subs",
".",
"topic",
"==",
"topic",
"&&",
"subs",
".",
"connectionName",
"==",
"name",
"{",
"topicFound",
"=",
"true",
"\n",
"mux",
".",
"mapping",
"=",
"append",
"(",
"mux",
".",
"mapping",
"[",
":",
"index",
"]",
",",
"mux",
".",
"mapping",
"[",
"index",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"topicFound",
"{",
"wasError",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"topic",
",",
"name",
")",
"\n",
"}",
"\n",
"return",
"wasError",
"\n",
"}"
] | // Remove consumer subscription on given topic. If there is no such a subscription, return error. | [
"Remove",
"consumer",
"subscription",
"on",
"given",
"topic",
".",
"If",
"there",
"is",
"no",
"such",
"a",
"subscription",
"return",
"error",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/multiplexer.go#L331-L347 |
4,747 | ligato/cn-infra | examples/kafka-plugin/hash-partitioner/main.go | asyncEventHandler | func (plugin *ExamplePlugin) asyncEventHandler() {
plugin.Log.Info("Started Kafka async event handler...")
msgCounter := 0
asyncMsgSucc := 0
if messageCountNum == 0 {
// Set as done
plugin.asyncSuccess = true
plugin.asyncRecv = true
}
for {
select {
// Channel subscribed with watcher
case message := <-plugin.asyncSubscription:
plugin.Log.Infof("Received async Kafka Message, topic '%s', partition '%v', offset '%v', key: '%s', ",
message.GetTopic(), message.GetPartition(), message.GetOffset(), message.GetKey())
// mark the offset
plugin.kafkaWatcher.MarkOffset(message, "")
msgCounter++
if msgCounter == messageCountNum {
plugin.asyncRecv = true
}
case message := <-plugin.asyncSuccessChannel:
plugin.Log.Infof("Async message successfully delivered, topic '%s', partition '%v', offset '%v', key: '%s', ",
message.GetTopic(), message.GetPartition(), message.GetOffset(), message.GetKey())
asyncMsgSucc++
if asyncMsgSucc == messageCountNum {
plugin.asyncSuccess = true
}
// Error callback channel
case err := <-plugin.asyncErrorChannel:
plugin.Log.Errorf("Failed to publish async message, %v", err)
}
}
} | go | func (plugin *ExamplePlugin) asyncEventHandler() {
plugin.Log.Info("Started Kafka async event handler...")
msgCounter := 0
asyncMsgSucc := 0
if messageCountNum == 0 {
// Set as done
plugin.asyncSuccess = true
plugin.asyncRecv = true
}
for {
select {
// Channel subscribed with watcher
case message := <-plugin.asyncSubscription:
plugin.Log.Infof("Received async Kafka Message, topic '%s', partition '%v', offset '%v', key: '%s', ",
message.GetTopic(), message.GetPartition(), message.GetOffset(), message.GetKey())
// mark the offset
plugin.kafkaWatcher.MarkOffset(message, "")
msgCounter++
if msgCounter == messageCountNum {
plugin.asyncRecv = true
}
case message := <-plugin.asyncSuccessChannel:
plugin.Log.Infof("Async message successfully delivered, topic '%s', partition '%v', offset '%v', key: '%s', ",
message.GetTopic(), message.GetPartition(), message.GetOffset(), message.GetKey())
asyncMsgSucc++
if asyncMsgSucc == messageCountNum {
plugin.asyncSuccess = true
}
// Error callback channel
case err := <-plugin.asyncErrorChannel:
plugin.Log.Errorf("Failed to publish async message, %v", err)
}
}
} | [
"func",
"(",
"plugin",
"*",
"ExamplePlugin",
")",
"asyncEventHandler",
"(",
")",
"{",
"plugin",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"msgCounter",
":=",
"0",
"\n",
"asyncMsgSucc",
":=",
"0",
"\n",
"if",
"messageCountNum",
"==",
"0",
"{",
"// Set as done",
"plugin",
".",
"asyncSuccess",
"=",
"true",
"\n",
"plugin",
".",
"asyncRecv",
"=",
"true",
"\n",
"}",
"\n",
"for",
"{",
"select",
"{",
"// Channel subscribed with watcher",
"case",
"message",
":=",
"<-",
"plugin",
".",
"asyncSubscription",
":",
"plugin",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"message",
".",
"GetTopic",
"(",
")",
",",
"message",
".",
"GetPartition",
"(",
")",
",",
"message",
".",
"GetOffset",
"(",
")",
",",
"message",
".",
"GetKey",
"(",
")",
")",
"\n",
"// mark the offset",
"plugin",
".",
"kafkaWatcher",
".",
"MarkOffset",
"(",
"message",
",",
"\"",
"\"",
")",
"\n",
"msgCounter",
"++",
"\n",
"if",
"msgCounter",
"==",
"messageCountNum",
"{",
"plugin",
".",
"asyncRecv",
"=",
"true",
"\n",
"}",
"\n",
"case",
"message",
":=",
"<-",
"plugin",
".",
"asyncSuccessChannel",
":",
"plugin",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"message",
".",
"GetTopic",
"(",
")",
",",
"message",
".",
"GetPartition",
"(",
")",
",",
"message",
".",
"GetOffset",
"(",
")",
",",
"message",
".",
"GetKey",
"(",
")",
")",
"\n",
"asyncMsgSucc",
"++",
"\n",
"if",
"asyncMsgSucc",
"==",
"messageCountNum",
"{",
"plugin",
".",
"asyncSuccess",
"=",
"true",
"\n",
"}",
"\n",
"// Error callback channel",
"case",
"err",
":=",
"<-",
"plugin",
".",
"asyncErrorChannel",
":",
"plugin",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // asyncEventHandler is a Kafka consumer asynchronously processing events from
// a channel associated with a specific topic. If a producer sends a message
// matching this destination criteria, the consumer will receive it. | [
"asyncEventHandler",
"is",
"a",
"Kafka",
"consumer",
"asynchronously",
"processing",
"events",
"from",
"a",
"channel",
"associated",
"with",
"a",
"specific",
"topic",
".",
"If",
"a",
"producer",
"sends",
"a",
"message",
"matching",
"this",
"destination",
"criteria",
"the",
"consumer",
"will",
"receive",
"it",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/kafka-plugin/hash-partitioner/main.go#L280-L313 |
4,748 | ligato/cn-infra | rpc/rest/options.go | UseAuthenticator | func UseAuthenticator(a BasicHTTPAuthenticator) Option {
return func(p *Plugin) {
p.Deps.Authenticator = a
}
} | go | func UseAuthenticator(a BasicHTTPAuthenticator) Option {
return func(p *Plugin) {
p.Deps.Authenticator = a
}
} | [
"func",
"UseAuthenticator",
"(",
"a",
"BasicHTTPAuthenticator",
")",
"Option",
"{",
"return",
"func",
"(",
"p",
"*",
"Plugin",
")",
"{",
"p",
".",
"Deps",
".",
"Authenticator",
"=",
"a",
"\n",
"}",
"\n",
"}"
] | // UseAuthenticator returns an Option which sets HTTP Authenticator. | [
"UseAuthenticator",
"returns",
"an",
"Option",
"which",
"sets",
"HTTP",
"Authenticator",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/options.go#L69-L73 |
4,749 | ligato/cn-infra | db/keyval/etcd/plugin_impl_etcd.go | AfterInit | func (p *Plugin) AfterInit() error {
if p.StatusCheck != nil && !p.disabled {
p.StatusCheck.Register(p.PluginName, p.statusCheckProbe)
p.Log.Infof("Status check for %s was started", p.PluginName)
}
return nil
} | go | func (p *Plugin) AfterInit() error {
if p.StatusCheck != nil && !p.disabled {
p.StatusCheck.Register(p.PluginName, p.statusCheckProbe)
p.Log.Infof("Status check for %s was started", p.PluginName)
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"AfterInit",
"(",
")",
"error",
"{",
"if",
"p",
".",
"StatusCheck",
"!=",
"nil",
"&&",
"!",
"p",
".",
"disabled",
"{",
"p",
".",
"StatusCheck",
".",
"Register",
"(",
"p",
".",
"PluginName",
",",
"p",
".",
"statusCheckProbe",
")",
"\n",
"p",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"p",
".",
"PluginName",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // AfterInit registers ETCD plugin to status check if needed | [
"AfterInit",
"registers",
"ETCD",
"plugin",
"to",
"status",
"check",
"if",
"needed"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/plugin_impl_etcd.go#L117-L124 |
4,750 | ligato/cn-infra | db/keyval/etcd/plugin_impl_etcd.go | OnConnect | func (p *Plugin) OnConnect(callback func() error) {
p.Lock()
defer p.Unlock()
if p.connected {
if err := callback(); err != nil {
p.Log.Errorf("callback for OnConnect failed: %v", err)
}
} else {
p.onConnection = append(p.onConnection, callback)
}
} | go | func (p *Plugin) OnConnect(callback func() error) {
p.Lock()
defer p.Unlock()
if p.connected {
if err := callback(); err != nil {
p.Log.Errorf("callback for OnConnect failed: %v", err)
}
} else {
p.onConnection = append(p.onConnection, callback)
}
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"OnConnect",
"(",
"callback",
"func",
"(",
")",
"error",
")",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"p",
".",
"connected",
"{",
"if",
"err",
":=",
"callback",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"p",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"p",
".",
"onConnection",
"=",
"append",
"(",
"p",
".",
"onConnection",
",",
"callback",
")",
"\n",
"}",
"\n",
"}"
] | // OnConnect executes callback if plugin is connected, or gathers functions from all plugin with ETCD as dependency | [
"OnConnect",
"executes",
"callback",
"if",
"plugin",
"is",
"connected",
"or",
"gathers",
"functions",
"from",
"all",
"plugin",
"with",
"ETCD",
"as",
"dependency"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/plugin_impl_etcd.go#L148-L159 |
4,751 | ligato/cn-infra | db/keyval/etcd/plugin_impl_etcd.go | Compact | func (p *Plugin) Compact(rev ...int64) (toRev int64, err error) {
if p.connection != nil {
return p.connection.Compact(rev...)
}
return 0, fmt.Errorf("connection is not established")
} | go | func (p *Plugin) Compact(rev ...int64) (toRev int64, err error) {
if p.connection != nil {
return p.connection.Compact(rev...)
}
return 0, fmt.Errorf("connection is not established")
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Compact",
"(",
"rev",
"...",
"int64",
")",
"(",
"toRev",
"int64",
",",
"err",
"error",
")",
"{",
"if",
"p",
".",
"connection",
"!=",
"nil",
"{",
"return",
"p",
".",
"connection",
".",
"Compact",
"(",
"rev",
"...",
")",
"\n",
"}",
"\n",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Compact compatcs the ETCD database to the specific revision | [
"Compact",
"compatcs",
"the",
"ETCD",
"database",
"to",
"the",
"specific",
"revision"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/plugin_impl_etcd.go#L176-L181 |
4,752 | ligato/cn-infra | db/keyval/etcd/plugin_impl_etcd.go | etcdReconnectionLoop | func (p *Plugin) etcdReconnectionLoop(clientCfg *ClientConfig) {
var err error
// Set reconnect interval
interval := p.config.ReconnectInterval
if interval == 0 {
interval = defaultReconnectInterval
}
p.Log.Infof("ETCD server %s not reachable in init phase. Agent will continue to try to connect every %d second(s)",
p.config.Endpoints, interval)
for {
time.Sleep(interval)
p.Log.Infof("Connecting to ETCD %v ...", p.config.Endpoints)
p.connection, err = NewEtcdConnectionWithBytes(*clientCfg, p.Log)
if err != nil {
continue
}
p.setupPostInitConnection()
return
}
} | go | func (p *Plugin) etcdReconnectionLoop(clientCfg *ClientConfig) {
var err error
// Set reconnect interval
interval := p.config.ReconnectInterval
if interval == 0 {
interval = defaultReconnectInterval
}
p.Log.Infof("ETCD server %s not reachable in init phase. Agent will continue to try to connect every %d second(s)",
p.config.Endpoints, interval)
for {
time.Sleep(interval)
p.Log.Infof("Connecting to ETCD %v ...", p.config.Endpoints)
p.connection, err = NewEtcdConnectionWithBytes(*clientCfg, p.Log)
if err != nil {
continue
}
p.setupPostInitConnection()
return
}
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"etcdReconnectionLoop",
"(",
"clientCfg",
"*",
"ClientConfig",
")",
"{",
"var",
"err",
"error",
"\n",
"// Set reconnect interval",
"interval",
":=",
"p",
".",
"config",
".",
"ReconnectInterval",
"\n",
"if",
"interval",
"==",
"0",
"{",
"interval",
"=",
"defaultReconnectInterval",
"\n",
"}",
"\n",
"p",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"p",
".",
"config",
".",
"Endpoints",
",",
"interval",
")",
"\n",
"for",
"{",
"time",
".",
"Sleep",
"(",
"interval",
")",
"\n\n",
"p",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"p",
".",
"config",
".",
"Endpoints",
")",
"\n",
"p",
".",
"connection",
",",
"err",
"=",
"NewEtcdConnectionWithBytes",
"(",
"*",
"clientCfg",
",",
"p",
".",
"Log",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"p",
".",
"setupPostInitConnection",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // Method starts loop which attempt to connect to the ETCD. If successful, send signal callback with resync,
// which will be started when datasync confirms successful registration | [
"Method",
"starts",
"loop",
"which",
"attempt",
"to",
"connect",
"to",
"the",
"ETCD",
".",
"If",
"successful",
"send",
"signal",
"callback",
"with",
"resync",
"which",
"will",
"be",
"started",
"when",
"datasync",
"confirms",
"successful",
"registration"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/plugin_impl_etcd.go#L185-L205 |
4,753 | ligato/cn-infra | db/keyval/etcd/plugin_impl_etcd.go | configureConnection | func (p *Plugin) configureConnection() {
if p.config.AutoCompact > 0 {
if p.config.AutoCompact < time.Duration(time.Minute*60) {
p.Log.Warnf("Auto compact option for ETCD is set to less than 60 minutes!")
}
p.startPeriodicAutoCompact(p.config.AutoCompact)
}
p.protoWrapper = kvproto.NewProtoWrapper(p.connection, &keyval.SerializerJSON{})
} | go | func (p *Plugin) configureConnection() {
if p.config.AutoCompact > 0 {
if p.config.AutoCompact < time.Duration(time.Minute*60) {
p.Log.Warnf("Auto compact option for ETCD is set to less than 60 minutes!")
}
p.startPeriodicAutoCompact(p.config.AutoCompact)
}
p.protoWrapper = kvproto.NewProtoWrapper(p.connection, &keyval.SerializerJSON{})
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"configureConnection",
"(",
")",
"{",
"if",
"p",
".",
"config",
".",
"AutoCompact",
">",
"0",
"{",
"if",
"p",
".",
"config",
".",
"AutoCompact",
"<",
"time",
".",
"Duration",
"(",
"time",
".",
"Minute",
"*",
"60",
")",
"{",
"p",
".",
"Log",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"p",
".",
"startPeriodicAutoCompact",
"(",
"p",
".",
"config",
".",
"AutoCompact",
")",
"\n",
"}",
"\n",
"p",
".",
"protoWrapper",
"=",
"kvproto",
".",
"NewProtoWrapper",
"(",
"p",
".",
"connection",
",",
"&",
"keyval",
".",
"SerializerJSON",
"{",
"}",
")",
"\n",
"}"
] | // If ETCD is connected, complete all other procedures | [
"If",
"ETCD",
"is",
"connected",
"complete",
"all",
"other",
"procedures"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/plugin_impl_etcd.go#L232-L240 |
4,754 | ligato/cn-infra | db/keyval/etcd/plugin_impl_etcd.go | statusCheckProbe | func (p *Plugin) statusCheckProbe() (statuscheck.PluginState, error) {
if p.connection == nil {
p.connected = false
return statuscheck.Error, fmt.Errorf("no ETCD connection available")
}
if _, _, _, err := p.connection.GetValue(healthCheckProbeKey); err != nil {
p.lastConnErr = err
p.connected = false
return statuscheck.Error, err
}
if p.config.ReconnectResync && p.lastConnErr != nil {
if p.Resync != nil {
p.Resync.DoResync()
p.lastConnErr = nil
} else {
p.Log.Warn("Expected resync after ETCD reconnect could not start beacuse of missing Resync plugin")
}
}
p.connected = true
return statuscheck.OK, nil
} | go | func (p *Plugin) statusCheckProbe() (statuscheck.PluginState, error) {
if p.connection == nil {
p.connected = false
return statuscheck.Error, fmt.Errorf("no ETCD connection available")
}
if _, _, _, err := p.connection.GetValue(healthCheckProbeKey); err != nil {
p.lastConnErr = err
p.connected = false
return statuscheck.Error, err
}
if p.config.ReconnectResync && p.lastConnErr != nil {
if p.Resync != nil {
p.Resync.DoResync()
p.lastConnErr = nil
} else {
p.Log.Warn("Expected resync after ETCD reconnect could not start beacuse of missing Resync plugin")
}
}
p.connected = true
return statuscheck.OK, nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"statusCheckProbe",
"(",
")",
"(",
"statuscheck",
".",
"PluginState",
",",
"error",
")",
"{",
"if",
"p",
".",
"connection",
"==",
"nil",
"{",
"p",
".",
"connected",
"=",
"false",
"\n",
"return",
"statuscheck",
".",
"Error",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"_",
",",
"_",
",",
"err",
":=",
"p",
".",
"connection",
".",
"GetValue",
"(",
"healthCheckProbeKey",
")",
";",
"err",
"!=",
"nil",
"{",
"p",
".",
"lastConnErr",
"=",
"err",
"\n",
"p",
".",
"connected",
"=",
"false",
"\n",
"return",
"statuscheck",
".",
"Error",
",",
"err",
"\n",
"}",
"\n",
"if",
"p",
".",
"config",
".",
"ReconnectResync",
"&&",
"p",
".",
"lastConnErr",
"!=",
"nil",
"{",
"if",
"p",
".",
"Resync",
"!=",
"nil",
"{",
"p",
".",
"Resync",
".",
"DoResync",
"(",
")",
"\n",
"p",
".",
"lastConnErr",
"=",
"nil",
"\n",
"}",
"else",
"{",
"p",
".",
"Log",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"p",
".",
"connected",
"=",
"true",
"\n",
"return",
"statuscheck",
".",
"OK",
",",
"nil",
"\n",
"}"
] | // ETCD status check probe function | [
"ETCD",
"status",
"check",
"probe",
"function"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/plugin_impl_etcd.go#L243-L263 |
4,755 | ligato/cn-infra | messaging/kafka/client/mocks.go | GetAsyncProducerMock | func GetAsyncProducerMock(t mocks.ErrorReporter) (*AsyncProducer, *mocks.AsyncProducer) {
saramaCfg := sarama.NewConfig()
saramaCfg.Producer.Return.Successes = true
mock := mocks.NewAsyncProducer(t, saramaCfg)
cfg := NewConfig(logrus.DefaultLogger())
cfg.SetSendSuccess(true)
cfg.SetSuccessChan(make(chan *ProducerMessage, 1))
ap := AsyncProducer{Logger: logrus.DefaultLogger(), Config: cfg, Producer: mock, closeChannel: make(chan struct{}), Client: &saramaClientMock{}}
go ap.successHandler(mock.Successes())
return &ap, mock
} | go | func GetAsyncProducerMock(t mocks.ErrorReporter) (*AsyncProducer, *mocks.AsyncProducer) {
saramaCfg := sarama.NewConfig()
saramaCfg.Producer.Return.Successes = true
mock := mocks.NewAsyncProducer(t, saramaCfg)
cfg := NewConfig(logrus.DefaultLogger())
cfg.SetSendSuccess(true)
cfg.SetSuccessChan(make(chan *ProducerMessage, 1))
ap := AsyncProducer{Logger: logrus.DefaultLogger(), Config: cfg, Producer: mock, closeChannel: make(chan struct{}), Client: &saramaClientMock{}}
go ap.successHandler(mock.Successes())
return &ap, mock
} | [
"func",
"GetAsyncProducerMock",
"(",
"t",
"mocks",
".",
"ErrorReporter",
")",
"(",
"*",
"AsyncProducer",
",",
"*",
"mocks",
".",
"AsyncProducer",
")",
"{",
"saramaCfg",
":=",
"sarama",
".",
"NewConfig",
"(",
")",
"\n",
"saramaCfg",
".",
"Producer",
".",
"Return",
".",
"Successes",
"=",
"true",
"\n",
"mock",
":=",
"mocks",
".",
"NewAsyncProducer",
"(",
"t",
",",
"saramaCfg",
")",
"\n\n",
"cfg",
":=",
"NewConfig",
"(",
"logrus",
".",
"DefaultLogger",
"(",
")",
")",
"\n",
"cfg",
".",
"SetSendSuccess",
"(",
"true",
")",
"\n",
"cfg",
".",
"SetSuccessChan",
"(",
"make",
"(",
"chan",
"*",
"ProducerMessage",
",",
"1",
")",
")",
"\n",
"ap",
":=",
"AsyncProducer",
"{",
"Logger",
":",
"logrus",
".",
"DefaultLogger",
"(",
")",
",",
"Config",
":",
"cfg",
",",
"Producer",
":",
"mock",
",",
"closeChannel",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"Client",
":",
"&",
"saramaClientMock",
"{",
"}",
"}",
"\n",
"go",
"ap",
".",
"successHandler",
"(",
"mock",
".",
"Successes",
"(",
")",
")",
"\n\n",
"return",
"&",
"ap",
",",
"mock",
"\n",
"}"
] | // GetAsyncProducerMock returns mocked implementation of async producer that doesn't
// need connection to Kafka broker and can be used for testing purposes. | [
"GetAsyncProducerMock",
"returns",
"mocked",
"implementation",
"of",
"async",
"producer",
"that",
"doesn",
"t",
"need",
"connection",
"to",
"Kafka",
"broker",
"and",
"can",
"be",
"used",
"for",
"testing",
"purposes",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/mocks.go#L36-L48 |
4,756 | ligato/cn-infra | messaging/kafka/client/mocks.go | GetSyncProducerMock | func GetSyncProducerMock(t mocks.ErrorReporter) (*SyncProducer, *mocks.SyncProducer) {
saramaCfg := sarama.NewConfig()
saramaCfg.Producer.Return.Successes = true
mock := mocks.NewSyncProducer(t, saramaCfg)
cfg := NewConfig(logrus.DefaultLogger())
ap := SyncProducer{Logger: logrus.DefaultLogger(), Config: cfg, Producer: mock, closeChannel: make(chan struct{}), Client: &saramaClientMock{}}
return &ap, mock
} | go | func GetSyncProducerMock(t mocks.ErrorReporter) (*SyncProducer, *mocks.SyncProducer) {
saramaCfg := sarama.NewConfig()
saramaCfg.Producer.Return.Successes = true
mock := mocks.NewSyncProducer(t, saramaCfg)
cfg := NewConfig(logrus.DefaultLogger())
ap := SyncProducer{Logger: logrus.DefaultLogger(), Config: cfg, Producer: mock, closeChannel: make(chan struct{}), Client: &saramaClientMock{}}
return &ap, mock
} | [
"func",
"GetSyncProducerMock",
"(",
"t",
"mocks",
".",
"ErrorReporter",
")",
"(",
"*",
"SyncProducer",
",",
"*",
"mocks",
".",
"SyncProducer",
")",
"{",
"saramaCfg",
":=",
"sarama",
".",
"NewConfig",
"(",
")",
"\n",
"saramaCfg",
".",
"Producer",
".",
"Return",
".",
"Successes",
"=",
"true",
"\n",
"mock",
":=",
"mocks",
".",
"NewSyncProducer",
"(",
"t",
",",
"saramaCfg",
")",
"\n\n",
"cfg",
":=",
"NewConfig",
"(",
"logrus",
".",
"DefaultLogger",
"(",
")",
")",
"\n",
"ap",
":=",
"SyncProducer",
"{",
"Logger",
":",
"logrus",
".",
"DefaultLogger",
"(",
")",
",",
"Config",
":",
"cfg",
",",
"Producer",
":",
"mock",
",",
"closeChannel",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"Client",
":",
"&",
"saramaClientMock",
"{",
"}",
"}",
"\n\n",
"return",
"&",
"ap",
",",
"mock",
"\n",
"}"
] | // GetSyncProducerMock returns mocked implementation of sync producer that doesn't need
// connection to Kafka broker and can be used for testing purposes. | [
"GetSyncProducerMock",
"returns",
"mocked",
"implementation",
"of",
"sync",
"producer",
"that",
"doesn",
"t",
"need",
"connection",
"to",
"Kafka",
"broker",
"and",
"can",
"be",
"used",
"for",
"testing",
"purposes",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/mocks.go#L52-L61 |
4,757 | ligato/cn-infra | messaging/kafka/client/mocks.go | GetConsumerMock | func GetConsumerMock(t mocks.ErrorReporter) *Consumer {
cfg := NewConfig(logrus.DefaultLogger())
ap := Consumer{
Logger: logrus.DefaultLogger(),
Config: cfg,
Consumer: newClusterConsumerMock(t),
closeChannel: make(chan struct{}),
}
return &ap
} | go | func GetConsumerMock(t mocks.ErrorReporter) *Consumer {
cfg := NewConfig(logrus.DefaultLogger())
ap := Consumer{
Logger: logrus.DefaultLogger(),
Config: cfg,
Consumer: newClusterConsumerMock(t),
closeChannel: make(chan struct{}),
}
return &ap
} | [
"func",
"GetConsumerMock",
"(",
"t",
"mocks",
".",
"ErrorReporter",
")",
"*",
"Consumer",
"{",
"cfg",
":=",
"NewConfig",
"(",
"logrus",
".",
"DefaultLogger",
"(",
")",
")",
"\n",
"ap",
":=",
"Consumer",
"{",
"Logger",
":",
"logrus",
".",
"DefaultLogger",
"(",
")",
",",
"Config",
":",
"cfg",
",",
"Consumer",
":",
"newClusterConsumerMock",
"(",
"t",
")",
",",
"closeChannel",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"}",
"\n\n",
"return",
"&",
"ap",
"\n",
"}"
] | // GetConsumerMock returns mocked implementation of consumer that doesn't need connection
// to kafka cluster. | [
"GetConsumerMock",
"returns",
"mocked",
"implementation",
"of",
"consumer",
"that",
"doesn",
"t",
"need",
"connection",
"to",
"kafka",
"cluster",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/mocks.go#L65-L75 |
4,758 | ligato/cn-infra | datasync/msgsync/plugin_impl_msgsync.go | AfterInit | func (p *Plugin) AfterInit() error {
if !p.Messaging.Disabled() {
cfg := p.Config
p.Cfg.LoadValue(&cfg)
if cfg.Topic != "" {
var err error
p.adapter, err = p.Messaging.NewSyncPublisher("msgsync-connection", cfg.Topic)
if err != nil {
return err
}
}
}
return nil
} | go | func (p *Plugin) AfterInit() error {
if !p.Messaging.Disabled() {
cfg := p.Config
p.Cfg.LoadValue(&cfg)
if cfg.Topic != "" {
var err error
p.adapter, err = p.Messaging.NewSyncPublisher("msgsync-connection", cfg.Topic)
if err != nil {
return err
}
}
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"AfterInit",
"(",
")",
"error",
"{",
"if",
"!",
"p",
".",
"Messaging",
".",
"Disabled",
"(",
")",
"{",
"cfg",
":=",
"p",
".",
"Config",
"\n",
"p",
".",
"Cfg",
".",
"LoadValue",
"(",
"&",
"cfg",
")",
"\n\n",
"if",
"cfg",
".",
"Topic",
"!=",
"\"",
"\"",
"{",
"var",
"err",
"error",
"\n",
"p",
".",
"adapter",
",",
"err",
"=",
"p",
".",
"Messaging",
".",
"NewSyncPublisher",
"(",
"\"",
"\"",
",",
"cfg",
".",
"Topic",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // AfterInit uses provided MUX connection to build new publisher. | [
"AfterInit",
"uses",
"provided",
"MUX",
"connection",
"to",
"build",
"new",
"publisher",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/msgsync/plugin_impl_msgsync.go#L54-L69 |
4,759 | ligato/cn-infra | processmanager/process_impl.go | deleteProcess | func (p *Process) deleteProcess() error {
if p.command == nil || p.command.Process == nil {
return nil
}
// Close the process watcher
if p.cancelChan != nil {
close(p.cancelChan)
}
p.log.Debugf("Process %s deleted", p.name)
return nil
} | go | func (p *Process) deleteProcess() error {
if p.command == nil || p.command.Process == nil {
return nil
}
// Close the process watcher
if p.cancelChan != nil {
close(p.cancelChan)
}
p.log.Debugf("Process %s deleted", p.name)
return nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"deleteProcess",
"(",
")",
"error",
"{",
"if",
"p",
".",
"command",
"==",
"nil",
"||",
"p",
".",
"command",
".",
"Process",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Close the process watcher",
"if",
"p",
".",
"cancelChan",
"!=",
"nil",
"{",
"close",
"(",
"p",
".",
"cancelChan",
")",
"\n",
"}",
"\n\n",
"p",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
".",
"name",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Delete stops the process and internal watcher | [
"Delete",
"stops",
"the",
"process",
"and",
"internal",
"watcher"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process_impl.go#L162-L174 |
4,760 | ligato/cn-infra | processmanager/process_impl.go | watch | func (p *Process) watch() {
if p.isWatched {
p.log.Warnf("Process watcher already running")
return
}
p.log.Debugf("Process %s watcher started", p.name)
p.isWatched = true
ticker := time.NewTicker(1 * time.Second)
var last status.ProcessStatus
var numRestarts int32
var autoTerm bool
if p.options != nil {
numRestarts = p.options.restart
autoTerm = p.options.autoTerm
}
for {
select {
case <-ticker.C:
var current status.ProcessStatus
// skip initial status since the process is not running yet
if current == status.Initial {
continue
}
if !p.isAlive() {
current = status.Terminated
} else {
pStatus, err := p.GetStatus(p.GetPid())
if err != nil {
p.log.Warn(err)
}
if pStatus.State == "" {
current = status.Unavailable
} else {
current = pStatus.State
}
}
// identify status change
if current != last {
if p.GetNotificationChan() != nil {
p.options.notifyChan <- current
}
// handle automatic process restarts
if current == status.Terminated {
if numRestarts > 0 || numRestarts == infiniteRestarts {
go func() {
var err error
if p.command, err = p.startProcess(); err != nil {
p.log.Error("attempt to restart process %s failed: %v", p.name, err)
}
}()
numRestarts--
} else {
p.log.Debugf("no more attempts to restart process %s", p.name)
}
}
// handle automatic zombie process cleanup
if current == status.Zombie && autoTerm {
p.log.Debugf("Terminating zombie process %d", p.GetPid())
if _, err := p.Wait(); err != nil {
p.log.Warnf("failed to terminate dead process: %s", p.GetPid(), err)
}
}
}
last = current
case <-p.cancelChan:
ticker.Stop()
p.closeNotifyChan()
return
}
}
} | go | func (p *Process) watch() {
if p.isWatched {
p.log.Warnf("Process watcher already running")
return
}
p.log.Debugf("Process %s watcher started", p.name)
p.isWatched = true
ticker := time.NewTicker(1 * time.Second)
var last status.ProcessStatus
var numRestarts int32
var autoTerm bool
if p.options != nil {
numRestarts = p.options.restart
autoTerm = p.options.autoTerm
}
for {
select {
case <-ticker.C:
var current status.ProcessStatus
// skip initial status since the process is not running yet
if current == status.Initial {
continue
}
if !p.isAlive() {
current = status.Terminated
} else {
pStatus, err := p.GetStatus(p.GetPid())
if err != nil {
p.log.Warn(err)
}
if pStatus.State == "" {
current = status.Unavailable
} else {
current = pStatus.State
}
}
// identify status change
if current != last {
if p.GetNotificationChan() != nil {
p.options.notifyChan <- current
}
// handle automatic process restarts
if current == status.Terminated {
if numRestarts > 0 || numRestarts == infiniteRestarts {
go func() {
var err error
if p.command, err = p.startProcess(); err != nil {
p.log.Error("attempt to restart process %s failed: %v", p.name, err)
}
}()
numRestarts--
} else {
p.log.Debugf("no more attempts to restart process %s", p.name)
}
}
// handle automatic zombie process cleanup
if current == status.Zombie && autoTerm {
p.log.Debugf("Terminating zombie process %d", p.GetPid())
if _, err := p.Wait(); err != nil {
p.log.Warnf("failed to terminate dead process: %s", p.GetPid(), err)
}
}
}
last = current
case <-p.cancelChan:
ticker.Stop()
p.closeNotifyChan()
return
}
}
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"watch",
"(",
")",
"{",
"if",
"p",
".",
"isWatched",
"{",
"p",
".",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"p",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
".",
"name",
")",
"\n",
"p",
".",
"isWatched",
"=",
"true",
"\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n\n",
"var",
"last",
"status",
".",
"ProcessStatus",
"\n",
"var",
"numRestarts",
"int32",
"\n",
"var",
"autoTerm",
"bool",
"\n",
"if",
"p",
".",
"options",
"!=",
"nil",
"{",
"numRestarts",
"=",
"p",
".",
"options",
".",
"restart",
"\n",
"autoTerm",
"=",
"p",
".",
"options",
".",
"autoTerm",
"\n",
"}",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"ticker",
".",
"C",
":",
"var",
"current",
"status",
".",
"ProcessStatus",
"\n",
"// skip initial status since the process is not running yet",
"if",
"current",
"==",
"status",
".",
"Initial",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"p",
".",
"isAlive",
"(",
")",
"{",
"current",
"=",
"status",
".",
"Terminated",
"\n",
"}",
"else",
"{",
"pStatus",
",",
"err",
":=",
"p",
".",
"GetStatus",
"(",
"p",
".",
"GetPid",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
".",
"log",
".",
"Warn",
"(",
"err",
")",
"\n",
"}",
"\n",
"if",
"pStatus",
".",
"State",
"==",
"\"",
"\"",
"{",
"current",
"=",
"status",
".",
"Unavailable",
"\n",
"}",
"else",
"{",
"current",
"=",
"pStatus",
".",
"State",
"\n",
"}",
"\n",
"}",
"\n",
"// identify status change",
"if",
"current",
"!=",
"last",
"{",
"if",
"p",
".",
"GetNotificationChan",
"(",
")",
"!=",
"nil",
"{",
"p",
".",
"options",
".",
"notifyChan",
"<-",
"current",
"\n",
"}",
"\n",
"// handle automatic process restarts",
"if",
"current",
"==",
"status",
".",
"Terminated",
"{",
"if",
"numRestarts",
">",
"0",
"||",
"numRestarts",
"==",
"infiniteRestarts",
"{",
"go",
"func",
"(",
")",
"{",
"var",
"err",
"error",
"\n",
"if",
"p",
".",
"command",
",",
"err",
"=",
"p",
".",
"startProcess",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"p",
".",
"log",
".",
"Error",
"(",
"\"",
"\"",
",",
"p",
".",
"name",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"numRestarts",
"--",
"\n",
"}",
"else",
"{",
"p",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
".",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// handle automatic zombie process cleanup",
"if",
"current",
"==",
"status",
".",
"Zombie",
"&&",
"autoTerm",
"{",
"p",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
".",
"GetPid",
"(",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"p",
".",
"Wait",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"p",
".",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"p",
".",
"GetPid",
"(",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"last",
"=",
"current",
"\n",
"case",
"<-",
"p",
".",
"cancelChan",
":",
"ticker",
".",
"Stop",
"(",
")",
"\n",
"p",
".",
"closeNotifyChan",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Periodically tries to 'ping' process. If the process is unresponsive, marks it as terminated. Otherwise the process
// status is updated. If process status was changed, notification is sent. In addition, terminated processes are
// restarted if allowed by policy, and dead processes are cleaned up. | [
"Periodically",
"tries",
"to",
"ping",
"process",
".",
"If",
"the",
"process",
"is",
"unresponsive",
"marks",
"it",
"as",
"terminated",
".",
"Otherwise",
"the",
"process",
"status",
"is",
"updated",
".",
"If",
"process",
"status",
"was",
"changed",
"notification",
"is",
"sent",
".",
"In",
"addition",
"terminated",
"processes",
"are",
"restarted",
"if",
"allowed",
"by",
"policy",
"and",
"dead",
"processes",
"are",
"cleaned",
"up",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process_impl.go#L188-L261 |
4,761 | ligato/cn-infra | examples/statuscheck-plugin/main.go | checkStatus | func (plugin *ExamplePlugin) checkStatus(closeCh chan struct{}) {
for {
select {
case <-closeCh:
plugin.Log.Info("Closing")
return
case <-time.After(1 * time.Second):
status := plugin.StatusMonitor.GetAllPluginStatus()
for k, v := range status {
plugin.Log.Infof("Status[%v] = %v", k, v)
}
}
}
} | go | func (plugin *ExamplePlugin) checkStatus(closeCh chan struct{}) {
for {
select {
case <-closeCh:
plugin.Log.Info("Closing")
return
case <-time.After(1 * time.Second):
status := plugin.StatusMonitor.GetAllPluginStatus()
for k, v := range status {
plugin.Log.Infof("Status[%v] = %v", k, v)
}
}
}
} | [
"func",
"(",
"plugin",
"*",
"ExamplePlugin",
")",
"checkStatus",
"(",
"closeCh",
"chan",
"struct",
"{",
"}",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"closeCh",
":",
"plugin",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"1",
"*",
"time",
".",
"Second",
")",
":",
"status",
":=",
"plugin",
".",
"StatusMonitor",
".",
"GetAllPluginStatus",
"(",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"status",
"{",
"plugin",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // checkStatus periodically prints status of plugins that publish their state
// to status check plugin | [
"checkStatus",
"periodically",
"prints",
"status",
"of",
"plugins",
"that",
"publish",
"their",
"state",
"to",
"status",
"check",
"plugin"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/statuscheck-plugin/main.go#L93-L106 |
4,762 | ligato/cn-infra | logging/logmanager/hooks.go | addHook | func (p *Plugin) addHook(hookName string, hookConfig HookConfig) error {
var lgHook logrus.Hook
var err error
switch hookName {
case HookSysLog:
address := hookConfig.Address
if hookConfig.Address != "" {
address = address + ":" + strconv.Itoa(hookConfig.Port)
}
lgHook, err = lgSyslog.NewSyslogHook(
hookConfig.Protocol,
address,
syslog.LOG_INFO,
p.ServiceLabel.GetAgentLabel(),
)
case HookLogStash:
lgHook, err = logrustash.NewHook(
hookConfig.Protocol,
hookConfig.Address+":"+strconv.Itoa(hookConfig.Port),
p.ServiceLabel.GetAgentLabel(),
)
case HookFluent:
lgHook, err = logrus_fluent.NewWithConfig(logrus_fluent.Config{
Host: hookConfig.Address,
Port: hookConfig.Port,
DefaultTag: p.ServiceLabel.GetAgentLabel(),
})
default:
return fmt.Errorf("unsupported hook: %q", hookName)
}
if err != nil {
return fmt.Errorf("creating hook for %v failed: %v", hookName, err)
}
// create hook
cHook := &commonHook{Hook: lgHook}
// fill up defined levels, or use default if not defined
if len(hookConfig.Levels) == 0 {
cHook.levels = []logrus.Level{logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel}
} else {
for _, level := range hookConfig.Levels {
if lgl, err := logrus.ParseLevel(level); err == nil {
cHook.levels = append(cHook.levels, lgl)
} else {
p.Log.Warnf("cannot parse hook log level %v : %v", level, err.Error())
}
}
}
// add hook to existing loggers and store it into registry for late use
p.LogRegistry.AddHook(cHook)
return nil
} | go | func (p *Plugin) addHook(hookName string, hookConfig HookConfig) error {
var lgHook logrus.Hook
var err error
switch hookName {
case HookSysLog:
address := hookConfig.Address
if hookConfig.Address != "" {
address = address + ":" + strconv.Itoa(hookConfig.Port)
}
lgHook, err = lgSyslog.NewSyslogHook(
hookConfig.Protocol,
address,
syslog.LOG_INFO,
p.ServiceLabel.GetAgentLabel(),
)
case HookLogStash:
lgHook, err = logrustash.NewHook(
hookConfig.Protocol,
hookConfig.Address+":"+strconv.Itoa(hookConfig.Port),
p.ServiceLabel.GetAgentLabel(),
)
case HookFluent:
lgHook, err = logrus_fluent.NewWithConfig(logrus_fluent.Config{
Host: hookConfig.Address,
Port: hookConfig.Port,
DefaultTag: p.ServiceLabel.GetAgentLabel(),
})
default:
return fmt.Errorf("unsupported hook: %q", hookName)
}
if err != nil {
return fmt.Errorf("creating hook for %v failed: %v", hookName, err)
}
// create hook
cHook := &commonHook{Hook: lgHook}
// fill up defined levels, or use default if not defined
if len(hookConfig.Levels) == 0 {
cHook.levels = []logrus.Level{logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel}
} else {
for _, level := range hookConfig.Levels {
if lgl, err := logrus.ParseLevel(level); err == nil {
cHook.levels = append(cHook.levels, lgl)
} else {
p.Log.Warnf("cannot parse hook log level %v : %v", level, err.Error())
}
}
}
// add hook to existing loggers and store it into registry for late use
p.LogRegistry.AddHook(cHook)
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"addHook",
"(",
"hookName",
"string",
",",
"hookConfig",
"HookConfig",
")",
"error",
"{",
"var",
"lgHook",
"logrus",
".",
"Hook",
"\n",
"var",
"err",
"error",
"\n\n",
"switch",
"hookName",
"{",
"case",
"HookSysLog",
":",
"address",
":=",
"hookConfig",
".",
"Address",
"\n",
"if",
"hookConfig",
".",
"Address",
"!=",
"\"",
"\"",
"{",
"address",
"=",
"address",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"hookConfig",
".",
"Port",
")",
"\n",
"}",
"\n",
"lgHook",
",",
"err",
"=",
"lgSyslog",
".",
"NewSyslogHook",
"(",
"hookConfig",
".",
"Protocol",
",",
"address",
",",
"syslog",
".",
"LOG_INFO",
",",
"p",
".",
"ServiceLabel",
".",
"GetAgentLabel",
"(",
")",
",",
")",
"\n",
"case",
"HookLogStash",
":",
"lgHook",
",",
"err",
"=",
"logrustash",
".",
"NewHook",
"(",
"hookConfig",
".",
"Protocol",
",",
"hookConfig",
".",
"Address",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"hookConfig",
".",
"Port",
")",
",",
"p",
".",
"ServiceLabel",
".",
"GetAgentLabel",
"(",
")",
",",
")",
"\n",
"case",
"HookFluent",
":",
"lgHook",
",",
"err",
"=",
"logrus_fluent",
".",
"NewWithConfig",
"(",
"logrus_fluent",
".",
"Config",
"{",
"Host",
":",
"hookConfig",
".",
"Address",
",",
"Port",
":",
"hookConfig",
".",
"Port",
",",
"DefaultTag",
":",
"p",
".",
"ServiceLabel",
".",
"GetAgentLabel",
"(",
")",
",",
"}",
")",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hookName",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hookName",
",",
"err",
")",
"\n",
"}",
"\n",
"// create hook",
"cHook",
":=",
"&",
"commonHook",
"{",
"Hook",
":",
"lgHook",
"}",
"\n",
"// fill up defined levels, or use default if not defined",
"if",
"len",
"(",
"hookConfig",
".",
"Levels",
")",
"==",
"0",
"{",
"cHook",
".",
"levels",
"=",
"[",
"]",
"logrus",
".",
"Level",
"{",
"logrus",
".",
"PanicLevel",
",",
"logrus",
".",
"FatalLevel",
",",
"logrus",
".",
"ErrorLevel",
"}",
"\n",
"}",
"else",
"{",
"for",
"_",
",",
"level",
":=",
"range",
"hookConfig",
".",
"Levels",
"{",
"if",
"lgl",
",",
"err",
":=",
"logrus",
".",
"ParseLevel",
"(",
"level",
")",
";",
"err",
"==",
"nil",
"{",
"cHook",
".",
"levels",
"=",
"append",
"(",
"cHook",
".",
"levels",
",",
"lgl",
")",
"\n",
"}",
"else",
"{",
"p",
".",
"Log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"level",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// add hook to existing loggers and store it into registry for late use",
"p",
".",
"LogRegistry",
".",
"AddHook",
"(",
"cHook",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // store hook into registy for late use and applies to existing loggers | [
"store",
"hook",
"into",
"registy",
"for",
"late",
"use",
"and",
"applies",
"to",
"existing",
"loggers"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logmanager/hooks.go#L33-L84 |
4,763 | ligato/cn-infra | logging/log_api.go | String | func (level LogLevel) String() string {
switch level {
case PanicLevel:
return "panic"
case FatalLevel:
return "fatal"
case ErrorLevel:
return "error"
case WarnLevel:
return "warn"
case InfoLevel:
return "info"
case DebugLevel:
return "debug"
default:
return fmt.Sprintf("unknown(%d)", level)
}
} | go | func (level LogLevel) String() string {
switch level {
case PanicLevel:
return "panic"
case FatalLevel:
return "fatal"
case ErrorLevel:
return "error"
case WarnLevel:
return "warn"
case InfoLevel:
return "info"
case DebugLevel:
return "debug"
default:
return fmt.Sprintf("unknown(%d)", level)
}
} | [
"func",
"(",
"level",
"LogLevel",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"level",
"{",
"case",
"PanicLevel",
":",
"return",
"\"",
"\"",
"\n",
"case",
"FatalLevel",
":",
"return",
"\"",
"\"",
"\n",
"case",
"ErrorLevel",
":",
"return",
"\"",
"\"",
"\n",
"case",
"WarnLevel",
":",
"return",
"\"",
"\"",
"\n",
"case",
"InfoLevel",
":",
"return",
"\"",
"\"",
"\n",
"case",
"DebugLevel",
":",
"return",
"\"",
"\"",
"\n",
"default",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"level",
")",
"\n",
"}",
"\n",
"}"
] | // String converts the LogLevel to a string. E.g. PanicLevel becomes "panic". | [
"String",
"converts",
"the",
"LogLevel",
"to",
"a",
"string",
".",
"E",
".",
"g",
".",
"PanicLevel",
"becomes",
"panic",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/log_api.go#L142-L159 |
4,764 | ligato/cn-infra | logging/log_api.go | ParseLogLevel | func ParseLogLevel(level string) LogLevel {
switch strings.ToLower(level) {
case "debug":
return DebugLevel
case "info":
return InfoLevel
case "warn", "warning":
return WarnLevel
case "error":
return ErrorLevel
case "fatal":
return FatalLevel
case "panic":
return PanicLevel
default:
return InfoLevel
}
} | go | func ParseLogLevel(level string) LogLevel {
switch strings.ToLower(level) {
case "debug":
return DebugLevel
case "info":
return InfoLevel
case "warn", "warning":
return WarnLevel
case "error":
return ErrorLevel
case "fatal":
return FatalLevel
case "panic":
return PanicLevel
default:
return InfoLevel
}
} | [
"func",
"ParseLogLevel",
"(",
"level",
"string",
")",
"LogLevel",
"{",
"switch",
"strings",
".",
"ToLower",
"(",
"level",
")",
"{",
"case",
"\"",
"\"",
":",
"return",
"DebugLevel",
"\n",
"case",
"\"",
"\"",
":",
"return",
"InfoLevel",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"return",
"WarnLevel",
"\n",
"case",
"\"",
"\"",
":",
"return",
"ErrorLevel",
"\n",
"case",
"\"",
"\"",
":",
"return",
"FatalLevel",
"\n",
"case",
"\"",
"\"",
":",
"return",
"PanicLevel",
"\n",
"default",
":",
"return",
"InfoLevel",
"\n",
"}",
"\n",
"}"
] | // ParseLogLevel parses string representation of LogLevel. | [
"ParseLogLevel",
"parses",
"string",
"representation",
"of",
"LogLevel",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/log_api.go#L162-L179 |
4,765 | ligato/cn-infra | logging/log_api.go | NewParentLogger | func NewParentLogger(name string, factory LoggerFactory) *ParentLogger {
return &ParentLogger{
Logger: factory.NewLogger(name),
Prefix: name,
Factory: factory,
}
} | go | func NewParentLogger(name string, factory LoggerFactory) *ParentLogger {
return &ParentLogger{
Logger: factory.NewLogger(name),
Prefix: name,
Factory: factory,
}
} | [
"func",
"NewParentLogger",
"(",
"name",
"string",
",",
"factory",
"LoggerFactory",
")",
"*",
"ParentLogger",
"{",
"return",
"&",
"ParentLogger",
"{",
"Logger",
":",
"factory",
".",
"NewLogger",
"(",
"name",
")",
",",
"Prefix",
":",
"name",
",",
"Factory",
":",
"factory",
",",
"}",
"\n",
"}"
] | // NewParentLogger creates new parent logger with given LoggerFactory and name as prefix. | [
"NewParentLogger",
"creates",
"new",
"parent",
"logger",
"with",
"given",
"LoggerFactory",
"and",
"name",
"as",
"prefix",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/log_api.go#L192-L198 |
4,766 | ligato/cn-infra | logging/log_api.go | NewLogger | func (p *ParentLogger) NewLogger(name string) Logger {
factory := p.Factory
if factory == nil {
factory = DefaultRegistry
}
return factory.NewLogger(fmt.Sprintf("%s.%s", p.Prefix, name))
} | go | func (p *ParentLogger) NewLogger(name string) Logger {
factory := p.Factory
if factory == nil {
factory = DefaultRegistry
}
return factory.NewLogger(fmt.Sprintf("%s.%s", p.Prefix, name))
} | [
"func",
"(",
"p",
"*",
"ParentLogger",
")",
"NewLogger",
"(",
"name",
"string",
")",
"Logger",
"{",
"factory",
":=",
"p",
".",
"Factory",
"\n",
"if",
"factory",
"==",
"nil",
"{",
"factory",
"=",
"DefaultRegistry",
"\n",
"}",
"\n",
"return",
"factory",
".",
"NewLogger",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
".",
"Prefix",
",",
"name",
")",
")",
"\n",
"}"
] | // NewLogger returns logger using name prefixed with prefix defined in parent logger.
// If Factory is nil, DefaultRegistry is used. | [
"NewLogger",
"returns",
"logger",
"using",
"name",
"prefixed",
"with",
"prefix",
"defined",
"in",
"parent",
"logger",
".",
"If",
"Factory",
"is",
"nil",
"DefaultRegistry",
"is",
"used",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/log_api.go#L202-L208 |
4,767 | ligato/cn-infra | messaging/kafka/plugin_impl_kafka.go | AfterInit | func (p *Plugin) AfterInit() error {
if p.disabled {
p.Log.Debugf("kafka plugin disabled, skipping AfterInit")
return nil
}
if p.mux != nil {
err := p.mux.Start()
if err != nil {
return err
}
}
// Register for providing status reports (polling mode)
if p.StatusCheck != nil {
p.StatusCheck.Register(p.PluginName, func() (statuscheck.PluginState, error) {
if p.hsClient == nil || p.hsClient.Closed() {
return statuscheck.Error, fmt.Errorf("kafka client/consumer not available")
}
// Method 'RefreshMetadata()' returns error if kafka server is unavailable
err := p.hsClient.RefreshMetadata(topic)
if err == nil {
return statuscheck.OK, nil
}
p.Log.Errorf("Kafka server unavailable")
return statuscheck.Error, err
})
} else {
p.Log.Warnf("Unable to start status check for kafka")
}
return nil
} | go | func (p *Plugin) AfterInit() error {
if p.disabled {
p.Log.Debugf("kafka plugin disabled, skipping AfterInit")
return nil
}
if p.mux != nil {
err := p.mux.Start()
if err != nil {
return err
}
}
// Register for providing status reports (polling mode)
if p.StatusCheck != nil {
p.StatusCheck.Register(p.PluginName, func() (statuscheck.PluginState, error) {
if p.hsClient == nil || p.hsClient.Closed() {
return statuscheck.Error, fmt.Errorf("kafka client/consumer not available")
}
// Method 'RefreshMetadata()' returns error if kafka server is unavailable
err := p.hsClient.RefreshMetadata(topic)
if err == nil {
return statuscheck.OK, nil
}
p.Log.Errorf("Kafka server unavailable")
return statuscheck.Error, err
})
} else {
p.Log.Warnf("Unable to start status check for kafka")
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"AfterInit",
"(",
")",
"error",
"{",
"if",
"p",
".",
"disabled",
"{",
"p",
".",
"Log",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"mux",
"!=",
"nil",
"{",
"err",
":=",
"p",
".",
"mux",
".",
"Start",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Register for providing status reports (polling mode)",
"if",
"p",
".",
"StatusCheck",
"!=",
"nil",
"{",
"p",
".",
"StatusCheck",
".",
"Register",
"(",
"p",
".",
"PluginName",
",",
"func",
"(",
")",
"(",
"statuscheck",
".",
"PluginState",
",",
"error",
")",
"{",
"if",
"p",
".",
"hsClient",
"==",
"nil",
"||",
"p",
".",
"hsClient",
".",
"Closed",
"(",
")",
"{",
"return",
"statuscheck",
".",
"Error",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Method 'RefreshMetadata()' returns error if kafka server is unavailable",
"err",
":=",
"p",
".",
"hsClient",
".",
"RefreshMetadata",
"(",
"topic",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"statuscheck",
".",
"OK",
",",
"nil",
"\n",
"}",
"\n",
"p",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"statuscheck",
".",
"Error",
",",
"err",
"\n",
"}",
")",
"\n",
"}",
"else",
"{",
"p",
".",
"Log",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // AfterInit is called in the second phase of the initialization. The kafka multiplexerNewWatcher
// is started, all consumers have to be subscribed until this phase. | [
"AfterInit",
"is",
"called",
"in",
"the",
"second",
"phase",
"of",
"the",
"initialization",
".",
"The",
"kafka",
"multiplexerNewWatcher",
"is",
"started",
"all",
"consumers",
"have",
"to",
"be",
"subscribed",
"until",
"this",
"phase",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/plugin_impl_kafka.go#L113-L145 |
4,768 | ligato/cn-infra | messaging/kafka/plugin_impl_kafka.go | Close | func (p *Plugin) Close() error {
return safeclose.Close(p.hsClient, p.manClient, p.mux)
} | go | func (p *Plugin) Close() error {
return safeclose.Close(p.hsClient, p.manClient, p.mux)
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Close",
"(",
")",
"error",
"{",
"return",
"safeclose",
".",
"Close",
"(",
"p",
".",
"hsClient",
",",
"p",
".",
"manClient",
",",
"p",
".",
"mux",
")",
"\n",
"}"
] | // Close is called at plugin cleanup phase. | [
"Close",
"is",
"called",
"at",
"plugin",
"cleanup",
"phase",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/plugin_impl_kafka.go#L148-L150 |
4,769 | ligato/cn-infra | messaging/kafka/plugin_impl_kafka.go | NewSyncPublisher | func (p *Plugin) NewSyncPublisher(connectionName string, topic string) (messaging.ProtoPublisher, error) {
return p.NewProtoConnection(connectionName).NewSyncPublisher(topic)
} | go | func (p *Plugin) NewSyncPublisher(connectionName string, topic string) (messaging.ProtoPublisher, error) {
return p.NewProtoConnection(connectionName).NewSyncPublisher(topic)
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"NewSyncPublisher",
"(",
"connectionName",
"string",
",",
"topic",
"string",
")",
"(",
"messaging",
".",
"ProtoPublisher",
",",
"error",
")",
"{",
"return",
"p",
".",
"NewProtoConnection",
"(",
"connectionName",
")",
".",
"NewSyncPublisher",
"(",
"topic",
")",
"\n",
"}"
] | // NewSyncPublisher creates a publisher that allows to publish messages using synchronous API. The publisher creates
// new proto connection on multiplexer with default partitioner. | [
"NewSyncPublisher",
"creates",
"a",
"publisher",
"that",
"allows",
"to",
"publish",
"messages",
"using",
"synchronous",
"API",
".",
"The",
"publisher",
"creates",
"new",
"proto",
"connection",
"on",
"multiplexer",
"with",
"default",
"partitioner",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/plugin_impl_kafka.go#L180-L182 |
4,770 | ligato/cn-infra | messaging/kafka/plugin_impl_kafka.go | NewSyncPublisherToPartition | func (p *Plugin) NewSyncPublisherToPartition(connectionName string, topic string, partition int32) (messaging.ProtoPublisher, error) {
return p.NewProtoManualConnection(connectionName).NewSyncPublisherToPartition(topic, partition)
} | go | func (p *Plugin) NewSyncPublisherToPartition(connectionName string, topic string, partition int32) (messaging.ProtoPublisher, error) {
return p.NewProtoManualConnection(connectionName).NewSyncPublisherToPartition(topic, partition)
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"NewSyncPublisherToPartition",
"(",
"connectionName",
"string",
",",
"topic",
"string",
",",
"partition",
"int32",
")",
"(",
"messaging",
".",
"ProtoPublisher",
",",
"error",
")",
"{",
"return",
"p",
".",
"NewProtoManualConnection",
"(",
"connectionName",
")",
".",
"NewSyncPublisherToPartition",
"(",
"topic",
",",
"partition",
")",
"\n",
"}"
] | // NewSyncPublisherToPartition creates a publisher that allows to publish messages to custom partition using synchronous API.
// The publisher creates new proto connection on multiplexer with manual partitioner. | [
"NewSyncPublisherToPartition",
"creates",
"a",
"publisher",
"that",
"allows",
"to",
"publish",
"messages",
"to",
"custom",
"partition",
"using",
"synchronous",
"API",
".",
"The",
"publisher",
"creates",
"new",
"proto",
"connection",
"on",
"multiplexer",
"with",
"manual",
"partitioner",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/plugin_impl_kafka.go#L186-L188 |
4,771 | ligato/cn-infra | messaging/kafka/plugin_impl_kafka.go | NewAsyncPublisher | func (p *Plugin) NewAsyncPublisher(connectionName string, topic string, successClb func(messaging.ProtoMessage), errorClb func(messaging.ProtoMessageErr)) (messaging.ProtoPublisher, error) {
return p.NewProtoConnection(connectionName).NewAsyncPublisher(topic, successClb, errorClb)
} | go | func (p *Plugin) NewAsyncPublisher(connectionName string, topic string, successClb func(messaging.ProtoMessage), errorClb func(messaging.ProtoMessageErr)) (messaging.ProtoPublisher, error) {
return p.NewProtoConnection(connectionName).NewAsyncPublisher(topic, successClb, errorClb)
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"NewAsyncPublisher",
"(",
"connectionName",
"string",
",",
"topic",
"string",
",",
"successClb",
"func",
"(",
"messaging",
".",
"ProtoMessage",
")",
",",
"errorClb",
"func",
"(",
"messaging",
".",
"ProtoMessageErr",
")",
")",
"(",
"messaging",
".",
"ProtoPublisher",
",",
"error",
")",
"{",
"return",
"p",
".",
"NewProtoConnection",
"(",
"connectionName",
")",
".",
"NewAsyncPublisher",
"(",
"topic",
",",
"successClb",
",",
"errorClb",
")",
"\n",
"}"
] | // NewAsyncPublisher creates a publisher that allows to publish messages using asynchronous API. The publisher creates
// new proto connection on multiplexer with default partitioner. | [
"NewAsyncPublisher",
"creates",
"a",
"publisher",
"that",
"allows",
"to",
"publish",
"messages",
"using",
"asynchronous",
"API",
".",
"The",
"publisher",
"creates",
"new",
"proto",
"connection",
"on",
"multiplexer",
"with",
"default",
"partitioner",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/plugin_impl_kafka.go#L192-L194 |
4,772 | ligato/cn-infra | messaging/kafka/plugin_impl_kafka.go | NewAsyncPublisherToPartition | func (p *Plugin) NewAsyncPublisherToPartition(connectionName string, topic string, partition int32, successClb func(messaging.ProtoMessage), errorClb func(messaging.ProtoMessageErr)) (messaging.ProtoPublisher, error) {
return p.NewProtoManualConnection(connectionName).NewAsyncPublisherToPartition(topic, partition, successClb, errorClb)
} | go | func (p *Plugin) NewAsyncPublisherToPartition(connectionName string, topic string, partition int32, successClb func(messaging.ProtoMessage), errorClb func(messaging.ProtoMessageErr)) (messaging.ProtoPublisher, error) {
return p.NewProtoManualConnection(connectionName).NewAsyncPublisherToPartition(topic, partition, successClb, errorClb)
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"NewAsyncPublisherToPartition",
"(",
"connectionName",
"string",
",",
"topic",
"string",
",",
"partition",
"int32",
",",
"successClb",
"func",
"(",
"messaging",
".",
"ProtoMessage",
")",
",",
"errorClb",
"func",
"(",
"messaging",
".",
"ProtoMessageErr",
")",
")",
"(",
"messaging",
".",
"ProtoPublisher",
",",
"error",
")",
"{",
"return",
"p",
".",
"NewProtoManualConnection",
"(",
"connectionName",
")",
".",
"NewAsyncPublisherToPartition",
"(",
"topic",
",",
"partition",
",",
"successClb",
",",
"errorClb",
")",
"\n",
"}"
] | // NewAsyncPublisherToPartition creates a publisher that allows to publish messages to custom partition using asynchronous API.
// The publisher creates new proto connection on multiplexer with manual partitioner. | [
"NewAsyncPublisherToPartition",
"creates",
"a",
"publisher",
"that",
"allows",
"to",
"publish",
"messages",
"to",
"custom",
"partition",
"using",
"asynchronous",
"API",
".",
"The",
"publisher",
"creates",
"new",
"proto",
"connection",
"on",
"multiplexer",
"with",
"manual",
"partitioner",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/plugin_impl_kafka.go#L198-L200 |
4,773 | ligato/cn-infra | messaging/kafka/plugin_impl_kafka.go | getClientConfig | func (p *Plugin) getClientConfig(config *mux.Config, logger logging.Logger, topic string) (*client.Config, error) {
clientCfg := client.NewConfig(logger)
// Set brokers obtained from kafka config. In case there are none available, use a default one
if len(config.Addrs) > 0 {
clientCfg.SetBrokers(config.Addrs...)
} else {
clientCfg.SetBrokers(mux.DefAddress)
}
// Set group ID obtained from kafka config. In case there is none, use a service label
if config.GroupID != "" {
clientCfg.SetGroup(config.GroupID)
} else {
clientCfg.SetGroup(p.ServiceLabel.GetAgentLabel())
}
clientCfg.SetRecvMessageChan(p.subscription)
clientCfg.SetInitialOffset(sarama.OffsetNewest)
clientCfg.SetTopics(topic)
if config.TLS.Enabled {
p.Log.Info("TLS enabled")
tlsConfig, err := clienttls.CreateTLSConfig(config.TLS)
if err != nil {
return nil, err
}
clientCfg.SetTLS(tlsConfig)
}
return clientCfg, nil
} | go | func (p *Plugin) getClientConfig(config *mux.Config, logger logging.Logger, topic string) (*client.Config, error) {
clientCfg := client.NewConfig(logger)
// Set brokers obtained from kafka config. In case there are none available, use a default one
if len(config.Addrs) > 0 {
clientCfg.SetBrokers(config.Addrs...)
} else {
clientCfg.SetBrokers(mux.DefAddress)
}
// Set group ID obtained from kafka config. In case there is none, use a service label
if config.GroupID != "" {
clientCfg.SetGroup(config.GroupID)
} else {
clientCfg.SetGroup(p.ServiceLabel.GetAgentLabel())
}
clientCfg.SetRecvMessageChan(p.subscription)
clientCfg.SetInitialOffset(sarama.OffsetNewest)
clientCfg.SetTopics(topic)
if config.TLS.Enabled {
p.Log.Info("TLS enabled")
tlsConfig, err := clienttls.CreateTLSConfig(config.TLS)
if err != nil {
return nil, err
}
clientCfg.SetTLS(tlsConfig)
}
return clientCfg, nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"getClientConfig",
"(",
"config",
"*",
"mux",
".",
"Config",
",",
"logger",
"logging",
".",
"Logger",
",",
"topic",
"string",
")",
"(",
"*",
"client",
".",
"Config",
",",
"error",
")",
"{",
"clientCfg",
":=",
"client",
".",
"NewConfig",
"(",
"logger",
")",
"\n",
"// Set brokers obtained from kafka config. In case there are none available, use a default one",
"if",
"len",
"(",
"config",
".",
"Addrs",
")",
">",
"0",
"{",
"clientCfg",
".",
"SetBrokers",
"(",
"config",
".",
"Addrs",
"...",
")",
"\n",
"}",
"else",
"{",
"clientCfg",
".",
"SetBrokers",
"(",
"mux",
".",
"DefAddress",
")",
"\n",
"}",
"\n",
"// Set group ID obtained from kafka config. In case there is none, use a service label",
"if",
"config",
".",
"GroupID",
"!=",
"\"",
"\"",
"{",
"clientCfg",
".",
"SetGroup",
"(",
"config",
".",
"GroupID",
")",
"\n",
"}",
"else",
"{",
"clientCfg",
".",
"SetGroup",
"(",
"p",
".",
"ServiceLabel",
".",
"GetAgentLabel",
"(",
")",
")",
"\n",
"}",
"\n",
"clientCfg",
".",
"SetRecvMessageChan",
"(",
"p",
".",
"subscription",
")",
"\n",
"clientCfg",
".",
"SetInitialOffset",
"(",
"sarama",
".",
"OffsetNewest",
")",
"\n",
"clientCfg",
".",
"SetTopics",
"(",
"topic",
")",
"\n",
"if",
"config",
".",
"TLS",
".",
"Enabled",
"{",
"p",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"tlsConfig",
",",
"err",
":=",
"clienttls",
".",
"CreateTLSConfig",
"(",
"config",
".",
"TLS",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"clientCfg",
".",
"SetTLS",
"(",
"tlsConfig",
")",
"\n",
"}",
"\n",
"return",
"clientCfg",
",",
"nil",
"\n",
"}"
] | // Receive client config according to kafka config data | [
"Receive",
"client",
"config",
"according",
"to",
"kafka",
"config",
"data"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/plugin_impl_kafka.go#L218-L244 |
4,774 | ligato/cn-infra | datasync/syncbase/kv_iterator.go | NewKeyVal | func NewKeyVal(key string, value datasync.LazyValue, rev int64) *KeyVal {
return &KeyVal{key, value, rev}
} | go | func NewKeyVal(key string, value datasync.LazyValue, rev int64) *KeyVal {
return &KeyVal{key, value, rev}
} | [
"func",
"NewKeyVal",
"(",
"key",
"string",
",",
"value",
"datasync",
".",
"LazyValue",
",",
"rev",
"int64",
")",
"*",
"KeyVal",
"{",
"return",
"&",
"KeyVal",
"{",
"key",
",",
"value",
",",
"rev",
"}",
"\n",
"}"
] | // NewKeyVal creates a new instance of KeyVal. | [
"NewKeyVal",
"creates",
"a",
"new",
"instance",
"of",
"KeyVal",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/kv_iterator.go#L55-L57 |
4,775 | ligato/cn-infra | datasync/syncbase/kv_iterator.go | NewKeyValBytes | func NewKeyValBytes(key string, value []byte, rev int64) *KeyValBytes {
return &KeyValBytes{key, value, rev}
} | go | func NewKeyValBytes(key string, value []byte, rev int64) *KeyValBytes {
return &KeyValBytes{key, value, rev}
} | [
"func",
"NewKeyValBytes",
"(",
"key",
"string",
",",
"value",
"[",
"]",
"byte",
",",
"rev",
"int64",
")",
"*",
"KeyValBytes",
"{",
"return",
"&",
"KeyValBytes",
"{",
"key",
",",
"value",
",",
"rev",
"}",
"\n",
"}"
] | // NewKeyValBytes creates a new instance of KeyValBytes. | [
"NewKeyValBytes",
"creates",
"a",
"new",
"instance",
"of",
"KeyValBytes",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/kv_iterator.go#L89-L91 |
4,776 | ligato/cn-infra | db/keyval/filedb/filesystem/filesystem.go | CreateFile | func (fsh *Handler) CreateFile(file string) error {
path, _ := filepath.Split(file)
// Create path at first if necessary
if path != "" {
if err := os.MkdirAll(path, os.ModePerm); err != nil {
return errors.Errorf("failed to create path for file %s: %v", file, err)
}
}
sf, err := os.Create(file)
if err != nil {
return errors.Errorf("failed to create file %s: %v", file, err)
}
return sf.Close()
} | go | func (fsh *Handler) CreateFile(file string) error {
path, _ := filepath.Split(file)
// Create path at first if necessary
if path != "" {
if err := os.MkdirAll(path, os.ModePerm); err != nil {
return errors.Errorf("failed to create path for file %s: %v", file, err)
}
}
sf, err := os.Create(file)
if err != nil {
return errors.Errorf("failed to create file %s: %v", file, err)
}
return sf.Close()
} | [
"func",
"(",
"fsh",
"*",
"Handler",
")",
"CreateFile",
"(",
"file",
"string",
")",
"error",
"{",
"path",
",",
"_",
":=",
"filepath",
".",
"Split",
"(",
"file",
")",
"\n",
"// Create path at first if necessary",
"if",
"path",
"!=",
"\"",
"\"",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"path",
",",
"os",
".",
"ModePerm",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"sf",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"sf",
".",
"Close",
"(",
")",
"\n",
"}"
] | // CreateFile is an implementation of the file system API interface | [
"CreateFile",
"is",
"an",
"implementation",
"of",
"the",
"file",
"system",
"API",
"interface"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/filesystem.go#L57-L70 |
4,777 | ligato/cn-infra | db/keyval/filedb/filesystem/filesystem.go | ReadFile | func (fsh *Handler) ReadFile(file string) ([]byte, error) {
return ioutil.ReadFile(file)
} | go | func (fsh *Handler) ReadFile(file string) ([]byte, error) {
return ioutil.ReadFile(file)
} | [
"func",
"(",
"fsh",
"*",
"Handler",
")",
"ReadFile",
"(",
"file",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"ioutil",
".",
"ReadFile",
"(",
"file",
")",
"\n",
"}"
] | // ReadFile is an implementation of the file system API interface | [
"ReadFile",
"is",
"an",
"implementation",
"of",
"the",
"file",
"system",
"API",
"interface"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/filesystem.go#L73-L75 |
4,778 | ligato/cn-infra | db/keyval/filedb/filesystem/filesystem.go | WriteFile | func (fsh *Handler) WriteFile(file string, data []byte) error {
fileObj, err := os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to open status file %s for writing: %v", file, err)
}
defer fileObj.Close()
if _, err := fileObj.Write(data); err != nil {
return fmt.Errorf("failed to write status file %s for writing: %v", file, err)
}
return nil
} | go | func (fsh *Handler) WriteFile(file string, data []byte) error {
fileObj, err := os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to open status file %s for writing: %v", file, err)
}
defer fileObj.Close()
if _, err := fileObj.Write(data); err != nil {
return fmt.Errorf("failed to write status file %s for writing: %v", file, err)
}
return nil
} | [
"func",
"(",
"fsh",
"*",
"Handler",
")",
"WriteFile",
"(",
"file",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"fileObj",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"file",
",",
"os",
".",
"O_TRUNC",
"|",
"os",
".",
"O_WRONLY",
",",
"os",
".",
"ModePerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"fileObj",
".",
"Close",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"fileObj",
".",
"Write",
"(",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"file",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // WriteFile is an implementation of the file system API interface | [
"WriteFile",
"is",
"an",
"implementation",
"of",
"the",
"file",
"system",
"API",
"interface"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/filesystem.go#L78-L88 |
4,779 | ligato/cn-infra | db/keyval/filedb/filesystem/filesystem.go | FileExists | func (fsh *Handler) FileExists(file string) bool {
if _, err := os.Stat(file); os.IsNotExist(err) {
return false
}
return true
} | go | func (fsh *Handler) FileExists(file string) bool {
if _, err := os.Stat(file); os.IsNotExist(err) {
return false
}
return true
} | [
"func",
"(",
"fsh",
"*",
"Handler",
")",
"FileExists",
"(",
"file",
"string",
")",
"bool",
"{",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"file",
")",
";",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // FileExists is an implementation of the file system API interface | [
"FileExists",
"is",
"an",
"implementation",
"of",
"the",
"file",
"system",
"API",
"interface"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/filesystem.go#L91-L96 |
4,780 | ligato/cn-infra | db/keyval/filedb/filesystem/filesystem.go | GetFileNames | func (fsh *Handler) GetFileNames(paths []string) (files []string, err error) {
for _, path := range paths {
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info == nil || info.IsDir() {
return nil
}
files = append(files, path)
return nil
})
if err != nil {
err = errors.Errorf("failed to traverse through %s: %v", path, err)
}
}
return files, err
} | go | func (fsh *Handler) GetFileNames(paths []string) (files []string, err error) {
for _, path := range paths {
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info == nil || info.IsDir() {
return nil
}
files = append(files, path)
return nil
})
if err != nil {
err = errors.Errorf("failed to traverse through %s: %v", path, err)
}
}
return files, err
} | [
"func",
"(",
"fsh",
"*",
"Handler",
")",
"GetFileNames",
"(",
"paths",
"[",
"]",
"string",
")",
"(",
"files",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"for",
"_",
",",
"path",
":=",
"range",
"paths",
"{",
"err",
":=",
"filepath",
".",
"Walk",
"(",
"path",
",",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"info",
"==",
"nil",
"||",
"info",
".",
"IsDir",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"files",
"=",
"append",
"(",
"files",
",",
"path",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"files",
",",
"err",
"\n",
"}"
] | // GetFileNames is an implementation of the file system API interface | [
"GetFileNames",
"is",
"an",
"implementation",
"of",
"the",
"file",
"system",
"API",
"interface"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/filesystem.go#L99-L116 |
4,781 | ligato/cn-infra | db/keyval/filedb/filesystem/filesystem.go | Watch | func (fsh *Handler) Watch(paths []string, onEvent func(event fsnotify.Event), onClose func()) error {
var err error
fsh.watcher, err = fsnotify.NewWatcher()
if err != nil {
return errors.Errorf("failed to init fileDB file system watcher: %v", err)
}
for _, path := range paths {
fsh.watcher.Add(path)
}
go func() {
for {
select {
case event, ok := <-fsh.watcher.Events:
if !ok {
onClose()
return
}
onEvent(event)
case err := <-fsh.watcher.Errors:
if err != nil {
fsh.log.Errorf("filesystem notification error %v", err)
}
}
}
}()
return nil
} | go | func (fsh *Handler) Watch(paths []string, onEvent func(event fsnotify.Event), onClose func()) error {
var err error
fsh.watcher, err = fsnotify.NewWatcher()
if err != nil {
return errors.Errorf("failed to init fileDB file system watcher: %v", err)
}
for _, path := range paths {
fsh.watcher.Add(path)
}
go func() {
for {
select {
case event, ok := <-fsh.watcher.Events:
if !ok {
onClose()
return
}
onEvent(event)
case err := <-fsh.watcher.Errors:
if err != nil {
fsh.log.Errorf("filesystem notification error %v", err)
}
}
}
}()
return nil
} | [
"func",
"(",
"fsh",
"*",
"Handler",
")",
"Watch",
"(",
"paths",
"[",
"]",
"string",
",",
"onEvent",
"func",
"(",
"event",
"fsnotify",
".",
"Event",
")",
",",
"onClose",
"func",
"(",
")",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"fsh",
".",
"watcher",
",",
"err",
"=",
"fsnotify",
".",
"NewWatcher",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"paths",
"{",
"fsh",
".",
"watcher",
".",
"Add",
"(",
"path",
")",
"\n",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"event",
",",
"ok",
":=",
"<-",
"fsh",
".",
"watcher",
".",
"Events",
":",
"if",
"!",
"ok",
"{",
"onClose",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"onEvent",
"(",
"event",
")",
"\n",
"case",
"err",
":=",
"<-",
"fsh",
".",
"watcher",
".",
"Errors",
":",
"if",
"err",
"!=",
"nil",
"{",
"fsh",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Watch starts new filesystem notification watcher. All events from files are passed to 'onEvent' function.
// Function 'onClose' is called when event channel is closed. | [
"Watch",
"starts",
"new",
"filesystem",
"notification",
"watcher",
".",
"All",
"events",
"from",
"files",
"are",
"passed",
"to",
"onEvent",
"function",
".",
"Function",
"onClose",
"is",
"called",
"when",
"event",
"channel",
"is",
"closed",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/filesystem.go#L120-L148 |
4,782 | ligato/cn-infra | db/keyval/filedb/filesystem/filesystem.go | getFilesInPath | func (fsh *Handler) getFilesInPath(files []string, path string) error {
pathInfo, err := os.Stat(path)
if err != nil {
return errors.Errorf("failed to read path %s: %v", path, err)
}
if pathInfo.IsDir() {
pathList, err := ioutil.ReadDir(path)
if err != nil {
return errors.Errorf("failed to read directory %s: %v", path, err)
}
for _, nested := range pathList {
// Recursive call to process all the tree
if err := fsh.getFilesInPath(files, path+nested.Name()); err != nil {
return err
}
}
}
files = append(files, path)
return nil
} | go | func (fsh *Handler) getFilesInPath(files []string, path string) error {
pathInfo, err := os.Stat(path)
if err != nil {
return errors.Errorf("failed to read path %s: %v", path, err)
}
if pathInfo.IsDir() {
pathList, err := ioutil.ReadDir(path)
if err != nil {
return errors.Errorf("failed to read directory %s: %v", path, err)
}
for _, nested := range pathList {
// Recursive call to process all the tree
if err := fsh.getFilesInPath(files, path+nested.Name()); err != nil {
return err
}
}
}
files = append(files, path)
return nil
} | [
"func",
"(",
"fsh",
"*",
"Handler",
")",
"getFilesInPath",
"(",
"files",
"[",
"]",
"string",
",",
"path",
"string",
")",
"error",
"{",
"pathInfo",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"pathInfo",
".",
"IsDir",
"(",
")",
"{",
"pathList",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"nested",
":=",
"range",
"pathList",
"{",
"// Recursive call to process all the tree",
"if",
"err",
":=",
"fsh",
".",
"getFilesInPath",
"(",
"files",
",",
"path",
"+",
"nested",
".",
"Name",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"files",
"=",
"append",
"(",
"files",
",",
"path",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Processes given path. If the target is a file, it is stored in the file list. If the target
// is a directory, function is called recursively on nested paths in order to process the whole tree. | [
"Processes",
"given",
"path",
".",
"If",
"the",
"target",
"is",
"a",
"file",
"it",
"is",
"stored",
"in",
"the",
"file",
"list",
".",
"If",
"the",
"target",
"is",
"a",
"directory",
"function",
"is",
"called",
"recursively",
"on",
"nested",
"paths",
"in",
"order",
"to",
"process",
"the",
"whole",
"tree",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/filesystem.go#L157-L177 |
4,783 | ligato/cn-infra | messaging/kafka/mux/mock.go | Mock | func Mock(t *testing.T) *KafkaMock {
asyncP, aMock := client.GetAsyncProducerMock(t)
syncP, sMock := client.GetSyncProducerMock(t)
producers := multiplexerProducers{
syncP, syncP, asyncP, asyncP,
}
return &KafkaMock{
NewMultiplexer(getMockConsumerFactory(t), producers, &client.Config{}, "name", logrus.DefaultLogger()),
aMock, sMock}
} | go | func Mock(t *testing.T) *KafkaMock {
asyncP, aMock := client.GetAsyncProducerMock(t)
syncP, sMock := client.GetSyncProducerMock(t)
producers := multiplexerProducers{
syncP, syncP, asyncP, asyncP,
}
return &KafkaMock{
NewMultiplexer(getMockConsumerFactory(t), producers, &client.Config{}, "name", logrus.DefaultLogger()),
aMock, sMock}
} | [
"func",
"Mock",
"(",
"t",
"*",
"testing",
".",
"T",
")",
"*",
"KafkaMock",
"{",
"asyncP",
",",
"aMock",
":=",
"client",
".",
"GetAsyncProducerMock",
"(",
"t",
")",
"\n",
"syncP",
",",
"sMock",
":=",
"client",
".",
"GetSyncProducerMock",
"(",
"t",
")",
"\n",
"producers",
":=",
"multiplexerProducers",
"{",
"syncP",
",",
"syncP",
",",
"asyncP",
",",
"asyncP",
",",
"}",
"\n\n",
"return",
"&",
"KafkaMock",
"{",
"NewMultiplexer",
"(",
"getMockConsumerFactory",
"(",
"t",
")",
",",
"producers",
",",
"&",
"client",
".",
"Config",
"{",
"}",
",",
"\"",
"\"",
",",
"logrus",
".",
"DefaultLogger",
"(",
")",
")",
",",
"aMock",
",",
"sMock",
"}",
"\n",
"}"
] | // Mock returns mock of Multiplexer that can be used for testing purposes. | [
"Mock",
"returns",
"mock",
"of",
"Multiplexer",
"that",
"can",
"be",
"used",
"for",
"testing",
"purposes",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/mock.go#L32-L42 |
4,784 | ligato/cn-infra | examples/tutorials/06_plugin_lookup/plugin2.go | RegisterWorld | func (p *HelloUniverse) RegisterWorld(name string, size int) {
p.worlds[name] = size
log.Printf("World %s (size %d) was registered", name, size)
} | go | func (p *HelloUniverse) RegisterWorld(name string, size int) {
p.worlds[name] = size
log.Printf("World %s (size %d) was registered", name, size)
} | [
"func",
"(",
"p",
"*",
"HelloUniverse",
")",
"RegisterWorld",
"(",
"name",
"string",
",",
"size",
"int",
")",
"{",
"p",
".",
"worlds",
"[",
"name",
"]",
"=",
"size",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"name",
",",
"size",
")",
"\n",
"}"
] | // RegisterWorld is exported for other plugins to use | [
"RegisterWorld",
"is",
"exported",
"for",
"other",
"plugins",
"to",
"use"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/tutorials/06_plugin_lookup/plugin2.go#L39-L42 |
4,785 | ligato/cn-infra | utils/safeclose/safeclose.go | safeClose | func safeClose(obj interface{}) error {
defer func() {
if r := recover(); r != nil {
logrus.DefaultLogger().Error("Recovered in safeclose: ", r)
}
}()
// closerWithoutErr is similar interface to io.Closer, but Close() does not return error
type closerWithoutErr interface {
Close()
}
if val := reflect.ValueOf(obj); val.IsValid() && !val.IsNil() {
if closer, ok := obj.(*io.Closer); ok {
if closer != nil {
return (*closer).Close()
}
} else if closer, ok := obj.(io.Closer); ok {
if closer != nil {
return closer.Close()
}
} else if closer, ok := obj.(*closerWithoutErr); ok {
if closer != nil {
(*closer).Close()
}
} else if closer, ok := obj.(closerWithoutErr); ok {
if closer != nil {
closer.Close()
}
} else if reflect.TypeOf(obj).Kind() == reflect.Chan {
val.Close()
}
}
return nil
} | go | func safeClose(obj interface{}) error {
defer func() {
if r := recover(); r != nil {
logrus.DefaultLogger().Error("Recovered in safeclose: ", r)
}
}()
// closerWithoutErr is similar interface to io.Closer, but Close() does not return error
type closerWithoutErr interface {
Close()
}
if val := reflect.ValueOf(obj); val.IsValid() && !val.IsNil() {
if closer, ok := obj.(*io.Closer); ok {
if closer != nil {
return (*closer).Close()
}
} else if closer, ok := obj.(io.Closer); ok {
if closer != nil {
return closer.Close()
}
} else if closer, ok := obj.(*closerWithoutErr); ok {
if closer != nil {
(*closer).Close()
}
} else if closer, ok := obj.(closerWithoutErr); ok {
if closer != nil {
closer.Close()
}
} else if reflect.TypeOf(obj).Kind() == reflect.Chan {
val.Close()
}
}
return nil
} | [
"func",
"safeClose",
"(",
"obj",
"interface",
"{",
"}",
")",
"error",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"r",
":=",
"recover",
"(",
")",
";",
"r",
"!=",
"nil",
"{",
"logrus",
".",
"DefaultLogger",
"(",
")",
".",
"Error",
"(",
"\"",
"\"",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// closerWithoutErr is similar interface to io.Closer, but Close() does not return error",
"type",
"closerWithoutErr",
"interface",
"{",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"val",
":=",
"reflect",
".",
"ValueOf",
"(",
"obj",
")",
";",
"val",
".",
"IsValid",
"(",
")",
"&&",
"!",
"val",
".",
"IsNil",
"(",
")",
"{",
"if",
"closer",
",",
"ok",
":=",
"obj",
".",
"(",
"*",
"io",
".",
"Closer",
")",
";",
"ok",
"{",
"if",
"closer",
"!=",
"nil",
"{",
"return",
"(",
"*",
"closer",
")",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"closer",
",",
"ok",
":=",
"obj",
".",
"(",
"io",
".",
"Closer",
")",
";",
"ok",
"{",
"if",
"closer",
"!=",
"nil",
"{",
"return",
"closer",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"closer",
",",
"ok",
":=",
"obj",
".",
"(",
"*",
"closerWithoutErr",
")",
";",
"ok",
"{",
"if",
"closer",
"!=",
"nil",
"{",
"(",
"*",
"closer",
")",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"closer",
",",
"ok",
":=",
"obj",
".",
"(",
"closerWithoutErr",
")",
";",
"ok",
"{",
"if",
"closer",
"!=",
"nil",
"{",
"closer",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"reflect",
".",
"TypeOf",
"(",
"obj",
")",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Chan",
"{",
"val",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // safeClose closes closable object. | [
"safeClose",
"closes",
"closable",
"object",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/utils/safeclose/safeclose.go#L26-L62 |
4,786 | ligato/cn-infra | utils/safeclose/safeclose.go | Close | func Close(objs ...interface{}) error {
errs := make([]error, len(objs))
for i, obj := range objs {
errs[i] = safeClose(obj)
}
for _, err := range errs {
if err != nil {
return CloseErrors(errs)
}
}
return nil
} | go | func Close(objs ...interface{}) error {
errs := make([]error, len(objs))
for i, obj := range objs {
errs[i] = safeClose(obj)
}
for _, err := range errs {
if err != nil {
return CloseErrors(errs)
}
}
return nil
} | [
"func",
"Close",
"(",
"objs",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"errs",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"len",
"(",
"objs",
")",
")",
"\n\n",
"for",
"i",
",",
"obj",
":=",
"range",
"objs",
"{",
"errs",
"[",
"i",
"]",
"=",
"safeClose",
"(",
"obj",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"err",
":=",
"range",
"errs",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"CloseErrors",
"(",
"errs",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Close tries to close all objects and return all errors using CloseErrors if there are any. | [
"Close",
"tries",
"to",
"close",
"all",
"objects",
"and",
"return",
"all",
"errors",
"using",
"CloseErrors",
"if",
"there",
"are",
"any",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/utils/safeclose/safeclose.go#L65-L79 |
4,787 | ligato/cn-infra | examples/redis-lib/airport/airport.go | main | func main() {
var debug bool
var redisConfigPath string
// init example flags
flag.BoolVar(&debug, "debug", false, "Enable debugging")
flag.StringVar(&redisConfigPath, "redis-config", "", "Redis configuration file path")
flag.Parse()
log := logrus.DefaultLogger()
if debug {
log.SetLevel(logging.DebugLevel)
}
// load redis config file
redisConfig, err := redis.LoadConfig(redisConfigPath)
if err != nil {
log.Errorf("Failed to load Redis config file %s: %v", redisConfigPath, err)
return
}
airport := &Airport{
log: log,
airlines: []string{"AA", "DL", "SW", "UA"},
flightRadar: make(map[string]struct{}),
arrivalPrefix: "/redis/airport/arrival",
departurePrefix: "/redis/airport/departure",
hangarPrefix: "/redis/airport/hangar",
motions: []string{" ->", "<- "},
respChan: make(chan keyval.BytesWatchResp, 10),
closeChan: make(chan string),
}
doneChan := make(chan struct{})
if err := airport.init(redisConfig, doneChan); err != nil {
airport.log.Errorf("airport example error: %v", err)
} else {
airport.start()
}
} | go | func main() {
var debug bool
var redisConfigPath string
// init example flags
flag.BoolVar(&debug, "debug", false, "Enable debugging")
flag.StringVar(&redisConfigPath, "redis-config", "", "Redis configuration file path")
flag.Parse()
log := logrus.DefaultLogger()
if debug {
log.SetLevel(logging.DebugLevel)
}
// load redis config file
redisConfig, err := redis.LoadConfig(redisConfigPath)
if err != nil {
log.Errorf("Failed to load Redis config file %s: %v", redisConfigPath, err)
return
}
airport := &Airport{
log: log,
airlines: []string{"AA", "DL", "SW", "UA"},
flightRadar: make(map[string]struct{}),
arrivalPrefix: "/redis/airport/arrival",
departurePrefix: "/redis/airport/departure",
hangarPrefix: "/redis/airport/hangar",
motions: []string{" ->", "<- "},
respChan: make(chan keyval.BytesWatchResp, 10),
closeChan: make(chan string),
}
doneChan := make(chan struct{})
if err := airport.init(redisConfig, doneChan); err != nil {
airport.log.Errorf("airport example error: %v", err)
} else {
airport.start()
}
} | [
"func",
"main",
"(",
")",
"{",
"var",
"debug",
"bool",
"\n",
"var",
"redisConfigPath",
"string",
"\n\n",
"// init example flags",
"flag",
".",
"BoolVar",
"(",
"&",
"debug",
",",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n",
"flag",
".",
"StringVar",
"(",
"&",
"redisConfigPath",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"flag",
".",
"Parse",
"(",
")",
"\n\n",
"log",
":=",
"logrus",
".",
"DefaultLogger",
"(",
")",
"\n",
"if",
"debug",
"{",
"log",
".",
"SetLevel",
"(",
"logging",
".",
"DebugLevel",
")",
"\n",
"}",
"\n",
"// load redis config file",
"redisConfig",
",",
"err",
":=",
"redis",
".",
"LoadConfig",
"(",
"redisConfigPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"redisConfigPath",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"airport",
":=",
"&",
"Airport",
"{",
"log",
":",
"log",
",",
"airlines",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"flightRadar",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
",",
"arrivalPrefix",
":",
"\"",
"\"",
",",
"departurePrefix",
":",
"\"",
"\"",
",",
"hangarPrefix",
":",
"\"",
"\"",
",",
"motions",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"respChan",
":",
"make",
"(",
"chan",
"keyval",
".",
"BytesWatchResp",
",",
"10",
")",
",",
"closeChan",
":",
"make",
"(",
"chan",
"string",
")",
",",
"}",
"\n",
"doneChan",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"if",
"err",
":=",
"airport",
".",
"init",
"(",
"redisConfig",
",",
"doneChan",
")",
";",
"err",
"!=",
"nil",
"{",
"airport",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"airport",
".",
"start",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Initialize airport and start serving | [
"Initialize",
"airport",
"and",
"start",
"serving"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/redis-lib/airport/airport.go#L161-L198 |
4,788 | ligato/cn-infra | examples/redis-lib/airport/airport.go | init | func (a *Airport) init(config interface{}, doneChan chan struct{}) (err error) {
a.log.Info("Airport redis example. If you need more info about what is happening, run example with -debug=true")
rand.Seed(time.Now().UnixNano())
printHeaders()
setupFlightStatusFormat()
// prepare client to connect to the redis DB
a.client, err = redis.ConfigToClient(config)
if err != nil {
return fmt.Errorf("failed to create redis client: %v", err)
}
a.connection, err = redis.NewBytesConnection(a.client, a.log)
if err != nil {
return fmt.Errorf("failed to create connection from redis client: %v", err)
}
// prepare all the brokers and watchers in order to simulate airport
a.arrivalBroker = kvproto.NewProtoWrapper(a.connection).NewBroker(a.arrivalPrefix)
a.arrivalWatcher = kvproto.NewProtoWrapper(a.connection).NewWatcher(a.arrivalPrefix)
a.departureBroker = kvproto.NewProtoWrapper(a.connection).NewBroker(a.departurePrefix)
a.departureWatcher = kvproto.NewProtoWrapper(a.connection).NewWatcher(a.departurePrefix)
a.hangarBroker = kvproto.NewProtoWrapper(a.connection).NewBroker(a.hangarPrefix)
a.hangarWatcher = kvproto.NewProtoWrapper(a.connection).NewWatcher(a.hangarPrefix)
a.cleanUp(false)
// start watchers
a.arrivalChan = make(chan datasync.ProtoWatchResp, flightSlots)
if err := a.arrivalWatcher.Watch(keyval.ToChanProto(a.arrivalChan), nil, ""); err != nil {
return fmt.Errorf("failed to start 'arrival' watcher: %v", err)
}
a.departureChan = make(chan datasync.ProtoWatchResp, flightSlots)
if err := a.departureWatcher.Watch(keyval.ToChanProto(a.departureChan), nil, ""); err != nil {
return fmt.Errorf("failed to start 'departure' watcher: %v", err)
}
a.hangarChan = make(chan datasync.ProtoWatchResp, hangarSlots)
if err := a.hangarWatcher.Watch(keyval.ToChanProto(a.hangarChan), nil, ""); err != nil {
return fmt.Errorf("failed to start 'hangar' watcher: %v", err)
}
a.runwayChan = make(chan flight.Info, flightSlots)
return nil
} | go | func (a *Airport) init(config interface{}, doneChan chan struct{}) (err error) {
a.log.Info("Airport redis example. If you need more info about what is happening, run example with -debug=true")
rand.Seed(time.Now().UnixNano())
printHeaders()
setupFlightStatusFormat()
// prepare client to connect to the redis DB
a.client, err = redis.ConfigToClient(config)
if err != nil {
return fmt.Errorf("failed to create redis client: %v", err)
}
a.connection, err = redis.NewBytesConnection(a.client, a.log)
if err != nil {
return fmt.Errorf("failed to create connection from redis client: %v", err)
}
// prepare all the brokers and watchers in order to simulate airport
a.arrivalBroker = kvproto.NewProtoWrapper(a.connection).NewBroker(a.arrivalPrefix)
a.arrivalWatcher = kvproto.NewProtoWrapper(a.connection).NewWatcher(a.arrivalPrefix)
a.departureBroker = kvproto.NewProtoWrapper(a.connection).NewBroker(a.departurePrefix)
a.departureWatcher = kvproto.NewProtoWrapper(a.connection).NewWatcher(a.departurePrefix)
a.hangarBroker = kvproto.NewProtoWrapper(a.connection).NewBroker(a.hangarPrefix)
a.hangarWatcher = kvproto.NewProtoWrapper(a.connection).NewWatcher(a.hangarPrefix)
a.cleanUp(false)
// start watchers
a.arrivalChan = make(chan datasync.ProtoWatchResp, flightSlots)
if err := a.arrivalWatcher.Watch(keyval.ToChanProto(a.arrivalChan), nil, ""); err != nil {
return fmt.Errorf("failed to start 'arrival' watcher: %v", err)
}
a.departureChan = make(chan datasync.ProtoWatchResp, flightSlots)
if err := a.departureWatcher.Watch(keyval.ToChanProto(a.departureChan), nil, ""); err != nil {
return fmt.Errorf("failed to start 'departure' watcher: %v", err)
}
a.hangarChan = make(chan datasync.ProtoWatchResp, hangarSlots)
if err := a.hangarWatcher.Watch(keyval.ToChanProto(a.hangarChan), nil, ""); err != nil {
return fmt.Errorf("failed to start 'hangar' watcher: %v", err)
}
a.runwayChan = make(chan flight.Info, flightSlots)
return nil
} | [
"func",
"(",
"a",
"*",
"Airport",
")",
"init",
"(",
"config",
"interface",
"{",
"}",
",",
"doneChan",
"chan",
"struct",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"a",
".",
"log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"rand",
".",
"Seed",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n\n",
"printHeaders",
"(",
")",
"\n",
"setupFlightStatusFormat",
"(",
")",
"\n\n",
"// prepare client to connect to the redis DB",
"a",
".",
"client",
",",
"err",
"=",
"redis",
".",
"ConfigToClient",
"(",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"a",
".",
"connection",
",",
"err",
"=",
"redis",
".",
"NewBytesConnection",
"(",
"a",
".",
"client",
",",
"a",
".",
"log",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// prepare all the brokers and watchers in order to simulate airport",
"a",
".",
"arrivalBroker",
"=",
"kvproto",
".",
"NewProtoWrapper",
"(",
"a",
".",
"connection",
")",
".",
"NewBroker",
"(",
"a",
".",
"arrivalPrefix",
")",
"\n",
"a",
".",
"arrivalWatcher",
"=",
"kvproto",
".",
"NewProtoWrapper",
"(",
"a",
".",
"connection",
")",
".",
"NewWatcher",
"(",
"a",
".",
"arrivalPrefix",
")",
"\n\n",
"a",
".",
"departureBroker",
"=",
"kvproto",
".",
"NewProtoWrapper",
"(",
"a",
".",
"connection",
")",
".",
"NewBroker",
"(",
"a",
".",
"departurePrefix",
")",
"\n",
"a",
".",
"departureWatcher",
"=",
"kvproto",
".",
"NewProtoWrapper",
"(",
"a",
".",
"connection",
")",
".",
"NewWatcher",
"(",
"a",
".",
"departurePrefix",
")",
"\n\n",
"a",
".",
"hangarBroker",
"=",
"kvproto",
".",
"NewProtoWrapper",
"(",
"a",
".",
"connection",
")",
".",
"NewBroker",
"(",
"a",
".",
"hangarPrefix",
")",
"\n",
"a",
".",
"hangarWatcher",
"=",
"kvproto",
".",
"NewProtoWrapper",
"(",
"a",
".",
"connection",
")",
".",
"NewWatcher",
"(",
"a",
".",
"hangarPrefix",
")",
"\n\n",
"a",
".",
"cleanUp",
"(",
"false",
")",
"\n\n",
"// start watchers",
"a",
".",
"arrivalChan",
"=",
"make",
"(",
"chan",
"datasync",
".",
"ProtoWatchResp",
",",
"flightSlots",
")",
"\n",
"if",
"err",
":=",
"a",
".",
"arrivalWatcher",
".",
"Watch",
"(",
"keyval",
".",
"ToChanProto",
"(",
"a",
".",
"arrivalChan",
")",
",",
"nil",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"a",
".",
"departureChan",
"=",
"make",
"(",
"chan",
"datasync",
".",
"ProtoWatchResp",
",",
"flightSlots",
")",
"\n",
"if",
"err",
":=",
"a",
".",
"departureWatcher",
".",
"Watch",
"(",
"keyval",
".",
"ToChanProto",
"(",
"a",
".",
"departureChan",
")",
",",
"nil",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"a",
".",
"hangarChan",
"=",
"make",
"(",
"chan",
"datasync",
".",
"ProtoWatchResp",
",",
"hangarSlots",
")",
"\n",
"if",
"err",
":=",
"a",
".",
"hangarWatcher",
".",
"Watch",
"(",
"keyval",
".",
"ToChanProto",
"(",
"a",
".",
"hangarChan",
")",
",",
"nil",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"a",
".",
"runwayChan",
"=",
"make",
"(",
"chan",
"flight",
".",
"Info",
",",
"flightSlots",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Set all required brokers, watchers, prepare redis connection | [
"Set",
"all",
"required",
"brokers",
"watchers",
"prepare",
"redis",
"connection"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/redis-lib/airport/airport.go#L201-L247 |
4,789 | ligato/cn-infra | examples/redis-lib/airport/airport.go | processArrivals | func (a *Airport) processArrivals() {
for {
arrival, ok := <-a.arrivalChan
if !ok {
a.log.Errorf("arrival channel closed")
return
}
switch arrival.GetChangeType() {
case datasync.Put:
fl := flight.Info{}
if err := arrival.GetValue(&fl); err != nil {
a.log.Errorf("failed to get value for arrival flight: %v", err)
continue
}
fl.Status = flight.Status_arrival
a.runwayChan <- fl
case datasync.Delete:
a.log.Debugf("arrival %s deleted\n", arrival.GetKey())
}
}
} | go | func (a *Airport) processArrivals() {
for {
arrival, ok := <-a.arrivalChan
if !ok {
a.log.Errorf("arrival channel closed")
return
}
switch arrival.GetChangeType() {
case datasync.Put:
fl := flight.Info{}
if err := arrival.GetValue(&fl); err != nil {
a.log.Errorf("failed to get value for arrival flight: %v", err)
continue
}
fl.Status = flight.Status_arrival
a.runwayChan <- fl
case datasync.Delete:
a.log.Debugf("arrival %s deleted\n", arrival.GetKey())
}
}
} | [
"func",
"(",
"a",
"*",
"Airport",
")",
"processArrivals",
"(",
")",
"{",
"for",
"{",
"arrival",
",",
"ok",
":=",
"<-",
"a",
".",
"arrivalChan",
"\n",
"if",
"!",
"ok",
"{",
"a",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"switch",
"arrival",
".",
"GetChangeType",
"(",
")",
"{",
"case",
"datasync",
".",
"Put",
":",
"fl",
":=",
"flight",
".",
"Info",
"{",
"}",
"\n",
"if",
"err",
":=",
"arrival",
".",
"GetValue",
"(",
"&",
"fl",
")",
";",
"err",
"!=",
"nil",
"{",
"a",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"fl",
".",
"Status",
"=",
"flight",
".",
"Status_arrival",
"\n",
"a",
".",
"runwayChan",
"<-",
"fl",
"\n",
"case",
"datasync",
".",
"Delete",
":",
"a",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"arrival",
".",
"GetKey",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Wait for arrivals. Incoming flights are set to 'arrival' status and sent to runway. | [
"Wait",
"for",
"arrivals",
".",
"Incoming",
"flights",
"are",
"set",
"to",
"arrival",
"status",
"and",
"sent",
"to",
"runway",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/redis-lib/airport/airport.go#L295-L315 |
4,790 | ligato/cn-infra | examples/redis-lib/airport/airport.go | processDepartures | func (a *Airport) processDepartures() {
for {
departure, ok := <-a.departureChan
if !ok {
a.log.Errorf("departure channel closed")
return
}
switch departure.GetChangeType() {
case datasync.Put:
fl := flight.Info{}
if err := departure.GetValue(&fl); err != nil {
a.log.Errorf("failed to get value for departure flight: %v", err)
continue
}
fl.Status = flight.Status_departure
a.runwayChan <- fl
case datasync.Delete:
a.log.Debugf("departure %s deleted\n", departure.GetKey())
}
}
} | go | func (a *Airport) processDepartures() {
for {
departure, ok := <-a.departureChan
if !ok {
a.log.Errorf("departure channel closed")
return
}
switch departure.GetChangeType() {
case datasync.Put:
fl := flight.Info{}
if err := departure.GetValue(&fl); err != nil {
a.log.Errorf("failed to get value for departure flight: %v", err)
continue
}
fl.Status = flight.Status_departure
a.runwayChan <- fl
case datasync.Delete:
a.log.Debugf("departure %s deleted\n", departure.GetKey())
}
}
} | [
"func",
"(",
"a",
"*",
"Airport",
")",
"processDepartures",
"(",
")",
"{",
"for",
"{",
"departure",
",",
"ok",
":=",
"<-",
"a",
".",
"departureChan",
"\n",
"if",
"!",
"ok",
"{",
"a",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"switch",
"departure",
".",
"GetChangeType",
"(",
")",
"{",
"case",
"datasync",
".",
"Put",
":",
"fl",
":=",
"flight",
".",
"Info",
"{",
"}",
"\n",
"if",
"err",
":=",
"departure",
".",
"GetValue",
"(",
"&",
"fl",
")",
";",
"err",
"!=",
"nil",
"{",
"a",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"fl",
".",
"Status",
"=",
"flight",
".",
"Status_departure",
"\n",
"a",
".",
"runwayChan",
"<-",
"fl",
"\n",
"case",
"datasync",
".",
"Delete",
":",
"a",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\\n",
"\"",
",",
"departure",
".",
"GetKey",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Wait for departures. Outgoing flights are set to 'departure' and sent to runway | [
"Wait",
"for",
"departures",
".",
"Outgoing",
"flights",
"are",
"set",
"to",
"departure",
"and",
"sent",
"to",
"runway"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/redis-lib/airport/airport.go#L318-L338 |
4,791 | ligato/cn-infra | examples/redis-lib/airport/airport.go | processHangar | func (a *Airport) processHangar() {
for {
hangar, ok := <-a.hangarChan
if !ok {
a.log.Errorf("hangar channel closed")
return
}
switch hangar.GetChangeType() {
case datasync.Put:
a.log.Debugf("hangar %s updated", hangar.GetKey())
case datasync.Delete:
fl := flight.Info{}
if _, err := fmt.Sscanf(hangar.GetKey(), hangarKeyTemplate, &(fl.Airline), &(fl.Number), &(fl.Priority)); err != nil {
a.log.Errorf("error creating hangar key: %v", err)
continue
}
if err := a.departureBroker.Put(fmt.Sprintf(flightIDFormat, fl.Airline, fl.Number), &fl); err != nil {
a.log.Errorf("failed to put flight to departure broker: %v", err)
continue
}
}
}
} | go | func (a *Airport) processHangar() {
for {
hangar, ok := <-a.hangarChan
if !ok {
a.log.Errorf("hangar channel closed")
return
}
switch hangar.GetChangeType() {
case datasync.Put:
a.log.Debugf("hangar %s updated", hangar.GetKey())
case datasync.Delete:
fl := flight.Info{}
if _, err := fmt.Sscanf(hangar.GetKey(), hangarKeyTemplate, &(fl.Airline), &(fl.Number), &(fl.Priority)); err != nil {
a.log.Errorf("error creating hangar key: %v", err)
continue
}
if err := a.departureBroker.Put(fmt.Sprintf(flightIDFormat, fl.Airline, fl.Number), &fl); err != nil {
a.log.Errorf("failed to put flight to departure broker: %v", err)
continue
}
}
}
} | [
"func",
"(",
"a",
"*",
"Airport",
")",
"processHangar",
"(",
")",
"{",
"for",
"{",
"hangar",
",",
"ok",
":=",
"<-",
"a",
".",
"hangarChan",
"\n",
"if",
"!",
"ok",
"{",
"a",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"switch",
"hangar",
".",
"GetChangeType",
"(",
")",
"{",
"case",
"datasync",
".",
"Put",
":",
"a",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"hangar",
".",
"GetKey",
"(",
")",
")",
"\n",
"case",
"datasync",
".",
"Delete",
":",
"fl",
":=",
"flight",
".",
"Info",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"fmt",
".",
"Sscanf",
"(",
"hangar",
".",
"GetKey",
"(",
")",
",",
"hangarKeyTemplate",
",",
"&",
"(",
"fl",
".",
"Airline",
")",
",",
"&",
"(",
"fl",
".",
"Number",
")",
",",
"&",
"(",
"fl",
".",
"Priority",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"a",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"err",
":=",
"a",
".",
"departureBroker",
".",
"Put",
"(",
"fmt",
".",
"Sprintf",
"(",
"flightIDFormat",
",",
"fl",
".",
"Airline",
",",
"fl",
".",
"Number",
")",
",",
"&",
"fl",
")",
";",
"err",
"!=",
"nil",
"{",
"a",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Wait for hangar. Incoming flights are stored, outgoing are sent to departure. | [
"Wait",
"for",
"hangar",
".",
"Incoming",
"flights",
"are",
"stored",
"outgoing",
"are",
"sent",
"to",
"departure",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/redis-lib/airport/airport.go#L341-L363 |
4,792 | ligato/cn-infra | datasync/syncbase/msg/change_event.go | Done | func (ev *ChangeEvent) Done(err error) {
//TODO publish response to the topic
if err != nil {
logrus.DefaultLogger().Error(err)
}
} | go | func (ev *ChangeEvent) Done(err error) {
//TODO publish response to the topic
if err != nil {
logrus.DefaultLogger().Error(err)
}
} | [
"func",
"(",
"ev",
"*",
"ChangeEvent",
")",
"Done",
"(",
"err",
"error",
")",
"{",
"//TODO publish response to the topic",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"DefaultLogger",
"(",
")",
".",
"Error",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // Done does nothing yet. | [
"Done",
"does",
"nothing",
"yet",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/msg/change_event.go#L57-L62 |
4,793 | ligato/cn-infra | datasync/syncbase/msg/change_event.go | GetChangeType | func (ev *ChangeWatchResp) GetChangeType() datasync.Op {
if ev.message.OperationType == PutDel_DEL {
return datasync.Delete
}
return datasync.Put
} | go | func (ev *ChangeWatchResp) GetChangeType() datasync.Op {
if ev.message.OperationType == PutDel_DEL {
return datasync.Delete
}
return datasync.Put
} | [
"func",
"(",
"ev",
"*",
"ChangeWatchResp",
")",
"GetChangeType",
"(",
")",
"datasync",
".",
"Op",
"{",
"if",
"ev",
".",
"message",
".",
"OperationType",
"==",
"PutDel_DEL",
"{",
"return",
"datasync",
".",
"Delete",
"\n",
"}",
"\n\n",
"return",
"datasync",
".",
"Put",
"\n",
"}"
] | // GetChangeType - see the comment in implemented interface datasync.ChangeEvent. | [
"GetChangeType",
"-",
"see",
"the",
"comment",
"in",
"implemented",
"interface",
"datasync",
".",
"ChangeEvent",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/msg/change_event.go#L70-L76 |
4,794 | ligato/cn-infra | datasync/syncbase/msg/change_event.go | GetValue | func (ev *ChangeWatchResp) GetValue(val proto.Message) error {
return json.Unmarshal(ev.message.Content, val) //TODO use contentType...
} | go | func (ev *ChangeWatchResp) GetValue(val proto.Message) error {
return json.Unmarshal(ev.message.Content, val) //TODO use contentType...
} | [
"func",
"(",
"ev",
"*",
"ChangeWatchResp",
")",
"GetValue",
"(",
"val",
"proto",
".",
"Message",
")",
"error",
"{",
"return",
"json",
".",
"Unmarshal",
"(",
"ev",
".",
"message",
".",
"Content",
",",
"val",
")",
"//TODO use contentType...",
"\n",
"}"
] | // GetValue - see the comments in the interface datasync.ChangeEvent. | [
"GetValue",
"-",
"see",
"the",
"comments",
"in",
"the",
"interface",
"datasync",
".",
"ChangeEvent",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/msg/change_event.go#L89-L91 |
4,795 | ligato/cn-infra | datasync/grpcsync/grpc_watcher.go | NewAdapter | func NewAdapter(grpcServer *grpc.Server) *Adapter {
//TODO grpcServer.RegisterCodec(json.NewCodec(), "application/json")
adapter := &Adapter{
base: syncbase.NewRegistry(),
server: grpcServer,
}
msg.RegisterDataMsgServiceServer(grpcServer, &DataMsgServiceServer{adapter})
return adapter
} | go | func NewAdapter(grpcServer *grpc.Server) *Adapter {
//TODO grpcServer.RegisterCodec(json.NewCodec(), "application/json")
adapter := &Adapter{
base: syncbase.NewRegistry(),
server: grpcServer,
}
msg.RegisterDataMsgServiceServer(grpcServer, &DataMsgServiceServer{adapter})
return adapter
} | [
"func",
"NewAdapter",
"(",
"grpcServer",
"*",
"grpc",
".",
"Server",
")",
"*",
"Adapter",
"{",
"//TODO grpcServer.RegisterCodec(json.NewCodec(), \"application/json\")",
"adapter",
":=",
"&",
"Adapter",
"{",
"base",
":",
"syncbase",
".",
"NewRegistry",
"(",
")",
",",
"server",
":",
"grpcServer",
",",
"}",
"\n",
"msg",
".",
"RegisterDataMsgServiceServer",
"(",
"grpcServer",
",",
"&",
"DataMsgServiceServer",
"{",
"adapter",
"}",
")",
"\n\n",
"return",
"adapter",
"\n",
"}"
] | // NewAdapter creates a new instance of Adapter. | [
"NewAdapter",
"creates",
"a",
"new",
"instance",
"of",
"Adapter",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/grpcsync/grpc_watcher.go#L35-L44 |
4,796 | ligato/cn-infra | examples/redis-lib/simple/simple.go | Close | func (sr *SimpleRedis) Close() error {
return safeclose.Close(sr.client, sr.respChan, sr.closeChan)
} | go | func (sr *SimpleRedis) Close() error {
return safeclose.Close(sr.client, sr.respChan, sr.closeChan)
} | [
"func",
"(",
"sr",
"*",
"SimpleRedis",
")",
"Close",
"(",
")",
"error",
"{",
"return",
"safeclose",
".",
"Close",
"(",
"sr",
".",
"client",
",",
"sr",
".",
"respChan",
",",
"sr",
".",
"closeChan",
")",
"\n",
"}"
] | // Close close the redis client and watcher channels | [
"Close",
"close",
"the",
"redis",
"client",
"and",
"watcher",
"channels"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/redis-lib/simple/simple.go#L221-L223 |
4,797 | ligato/cn-infra | datasync/kvdbsync/options.go | UseKV | func UseKV(kv keyval.KvProtoPlugin) Option {
return func(p *Plugin) {
p.KvPlugin = kv
}
} | go | func UseKV(kv keyval.KvProtoPlugin) Option {
return func(p *Plugin) {
p.KvPlugin = kv
}
} | [
"func",
"UseKV",
"(",
"kv",
"keyval",
".",
"KvProtoPlugin",
")",
"Option",
"{",
"return",
"func",
"(",
"p",
"*",
"Plugin",
")",
"{",
"p",
".",
"KvPlugin",
"=",
"kv",
"\n",
"}",
"\n",
"}"
] | // UseKV returns Option that sets KvPlugin dependency. | [
"UseKV",
"returns",
"Option",
"that",
"sets",
"KvPlugin",
"dependency",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/kvdbsync/options.go#L62-L66 |
4,798 | ligato/cn-infra | db/keyval/kvproto/proto_watcher_impl.go | GetValue | func (wr *protoWatchResp) GetValue(msg proto.Message) error {
return wr.serializer.Unmarshal(wr.BytesWatchResp.GetValue(), msg)
} | go | func (wr *protoWatchResp) GetValue(msg proto.Message) error {
return wr.serializer.Unmarshal(wr.BytesWatchResp.GetValue(), msg)
} | [
"func",
"(",
"wr",
"*",
"protoWatchResp",
")",
"GetValue",
"(",
"msg",
"proto",
".",
"Message",
")",
"error",
"{",
"return",
"wr",
".",
"serializer",
".",
"Unmarshal",
"(",
"wr",
".",
"BytesWatchResp",
".",
"GetValue",
"(",
")",
",",
"msg",
")",
"\n",
"}"
] | // GetValue returns the value after the change. | [
"GetValue",
"returns",
"the",
"value",
"after",
"the",
"change",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/kvproto/proto_watcher_impl.go#L53-L55 |
4,799 | ligato/cn-infra | db/keyval/kvproto/proto_watcher_impl.go | GetPrevValue | func (wr *protoWatchResp) GetPrevValue(msg proto.Message) (prevValueExist bool, err error) {
prevVal := wr.BytesWatchResp.GetPrevValue()
if prevVal == nil {
return false, nil
}
err = wr.serializer.Unmarshal(prevVal, msg)
if err != nil {
return true, err
}
return true, nil
} | go | func (wr *protoWatchResp) GetPrevValue(msg proto.Message) (prevValueExist bool, err error) {
prevVal := wr.BytesWatchResp.GetPrevValue()
if prevVal == nil {
return false, nil
}
err = wr.serializer.Unmarshal(prevVal, msg)
if err != nil {
return true, err
}
return true, nil
} | [
"func",
"(",
"wr",
"*",
"protoWatchResp",
")",
"GetPrevValue",
"(",
"msg",
"proto",
".",
"Message",
")",
"(",
"prevValueExist",
"bool",
",",
"err",
"error",
")",
"{",
"prevVal",
":=",
"wr",
".",
"BytesWatchResp",
".",
"GetPrevValue",
"(",
")",
"\n",
"if",
"prevVal",
"==",
"nil",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"err",
"=",
"wr",
".",
"serializer",
".",
"Unmarshal",
"(",
"prevVal",
",",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"true",
",",
"err",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // GetPrevValue returns the previous value after the change. | [
"GetPrevValue",
"returns",
"the",
"previous",
"value",
"after",
"the",
"change",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/kvproto/proto_watcher_impl.go#L58-L68 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.