id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
4,400
ligato/cn-infra
db/sql/cassandra/query.go
cqlExportedWithFieldName
func cqlExportedWithFieldName(field *r.StructField) (fieldName string, exported bool) { cql := field.Tag.Get("cql") if len(cql) > 0 { if cql == "-" { return cql, false } return cql, true } return field.Name, true }
go
func cqlExportedWithFieldName(field *r.StructField) (fieldName string, exported bool) { cql := field.Tag.Get("cql") if len(cql) > 0 { if cql == "-" { return cql, false } return cql, true } return field.Name, true }
[ "func", "cqlExportedWithFieldName", "(", "field", "*", "r", ".", "StructField", ")", "(", "fieldName", "string", ",", "exported", "bool", ")", "{", "cql", ":=", "field", ".", "Tag", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "len", "(", "cql", ")"...
// cqlExportedWithFieldName checks the cql tag in StructField and parses the field name
[ "cqlExportedWithFieldName", "checks", "the", "cql", "tag", "in", "StructField", "and", "parses", "the", "field", "name" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/cassandra/query.go#L161-L170
4,401
ligato/cn-infra
db/sql/cassandra/query.go
isFieldPK
func isFieldPK(field *r.StructField) (isPK bool) { result := false pk := field.Tag.Get("pk") if len(pk) > 0 { result = true } return result }
go
func isFieldPK(field *r.StructField) (isPK bool) { result := false pk := field.Tag.Get("pk") if len(pk) > 0 { result = true } return result }
[ "func", "isFieldPK", "(", "field", "*", "r", ".", "StructField", ")", "(", "isPK", "bool", ")", "{", "result", ":=", "false", "\n", "pk", ":=", "field", ".", "Tag", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "len", "(", "pk", ")", ">", "0", ...
// isFieldPK checks the pk tag in StructField and parses the field name
[ "isFieldPK", "checks", "the", "pk", "tag", "in", "StructField", "and", "parses", "the", "field", "name" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/cassandra/query.go#L173-L180
4,402
ligato/cn-infra
db/sql/cassandra/query.go
selectFields
func selectFields(val interface{} /*, opts Options*/) (statement string) { fields := structs.ListExportedFields(val, cqlExported) ret := bytes.Buffer{} first := true for _, field := range fields { fieldName, exported := fieldName(field) if exported { if first { first = false } else { ret.WriteString(", ") } ret.WriteString(fieldName) } } return ret.String() }
go
func selectFields(val interface{} /*, opts Options*/) (statement string) { fields := structs.ListExportedFields(val, cqlExported) ret := bytes.Buffer{} first := true for _, field := range fields { fieldName, exported := fieldName(field) if exported { if first { first = false } else { ret.WriteString(", ") } ret.WriteString(fieldName) } } return ret.String() }
[ "func", "selectFields", "(", "val", "interface", "{", "}", "/*, opts Options*/", ")", "(", "statement", "string", ")", "{", "fields", ":=", "structs", ".", "ListExportedFields", "(", "val", ",", "cqlExported", ")", "\n", "ret", ":=", "bytes", ".", "Buffer", ...
// selectFields generates comma separated field names string
[ "selectFields", "generates", "comma", "separated", "field", "names", "string" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/cassandra/query.go#L197-L215
4,403
ligato/cn-infra
db/sql/cassandra/query.go
updateSetExpToString
func updateSetExpToString(cfName string, val interface{} /*, opts Options*/) ( statement string, fields []string, err error) { fields = sliceOfFieldNames(val) statement = updateStatement(cfName, fields) return statement, fields, nil }
go
func updateSetExpToString(cfName string, val interface{} /*, opts Options*/) ( statement string, fields []string, err error) { fields = sliceOfFieldNames(val) statement = updateStatement(cfName, fields) return statement, fields, nil }
[ "func", "updateSetExpToString", "(", "cfName", "string", ",", "val", "interface", "{", "}", "/*, opts Options*/", ")", "(", "statement", "string", ",", "fields", "[", "]", "string", ",", "err", "error", ")", "{", "fields", "=", "sliceOfFieldNames", "(", "val...
// updateSetExpToString generates UPDATE + SET part of SQL statement // for fields of an entity
[ "updateSetExpToString", "generates", "UPDATE", "+", "SET", "part", "of", "SQL", "statement", "for", "fields", "of", "an", "entity" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/cassandra/query.go#L250-L257
4,404
ligato/cn-infra
db/sql/cassandra/query.go
updateStatement
func updateStatement(cfName string, fields []string /*, opts Options*/) (statement string) { buf := new(bytes.Buffer) buf.WriteString(fmt.Sprintf("UPDATE %s ", cfName)) /* // Apply options if opts.TTL != 0 { buf.WriteString("USING TTL ") buf.WriteString(strconv.FormatFloat(opts.TTL.Seconds(), 'f', 0, 64)) buf.WriteRune(' ') }*/ buf.WriteString("SET ") first := true for _, fieldName := range fields { if !first { buf.WriteString(", ") } else { first = false } buf.WriteString(fieldName) buf.WriteString(` = ?`) } return buf.String() }
go
func updateStatement(cfName string, fields []string /*, opts Options*/) (statement string) { buf := new(bytes.Buffer) buf.WriteString(fmt.Sprintf("UPDATE %s ", cfName)) /* // Apply options if opts.TTL != 0 { buf.WriteString("USING TTL ") buf.WriteString(strconv.FormatFloat(opts.TTL.Seconds(), 'f', 0, 64)) buf.WriteRune(' ') }*/ buf.WriteString("SET ") first := true for _, fieldName := range fields { if !first { buf.WriteString(", ") } else { first = false } buf.WriteString(fieldName) buf.WriteString(` = ?`) } return buf.String() }
[ "func", "updateStatement", "(", "cfName", "string", ",", "fields", "[", "]", "string", "/*, opts Options*/", ")", "(", "statement", "string", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "buf", ".", "WriteString", "(", "fmt", "."...
// UPDATE keyspace.Movies SET col1 = val1, col2 = val2
[ "UPDATE", "keyspace", ".", "Movies", "SET", "col1", "=", "val1", "col2", "=", "val2" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/cassandra/query.go#L260-L285
4,405
ligato/cn-infra
db/sql/cassandra/query.go
VisitPrefixedExp
func (visitor *findEntityVisitor) VisitPrefixedExp(exp *sql.PrefixedExp) { if exp.Prefix == "FROM" { if len(exp.Binding) == 1 && r.Indirect(r.ValueOf(exp.Binding[0])).Kind() == r.Struct { visitor.entity = exp.Binding[0] } } else if exp.AfterPrefix != nil { for _, exp := range exp.AfterPrefix { exp.Accept(visitor) } } }
go
func (visitor *findEntityVisitor) VisitPrefixedExp(exp *sql.PrefixedExp) { if exp.Prefix == "FROM" { if len(exp.Binding) == 1 && r.Indirect(r.ValueOf(exp.Binding[0])).Kind() == r.Struct { visitor.entity = exp.Binding[0] } } else if exp.AfterPrefix != nil { for _, exp := range exp.AfterPrefix { exp.Accept(visitor) } } }
[ "func", "(", "visitor", "*", "findEntityVisitor", ")", "VisitPrefixedExp", "(", "exp", "*", "sql", ".", "PrefixedExp", ")", "{", "if", "exp", ".", "Prefix", "==", "\"", "\"", "{", "if", "len", "(", "exp", ".", "Binding", ")", "==", "1", "&&", "r", ...
// VisitPrefixedExp checks for "FROM" expression to find out the entity
[ "VisitPrefixedExp", "checks", "for", "FROM", "expression", "to", "find", "out", "the", "entity" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/cassandra/query.go#L292-L302
4,406
ligato/cn-infra
db/sql/cassandra/query.go
VisitFieldExpression
func (visitor *findEntityVisitor) VisitFieldExpression(exp *sql.FieldExpression) { if exp.AfterField != nil { exp.AfterField.Accept(visitor) } }
go
func (visitor *findEntityVisitor) VisitFieldExpression(exp *sql.FieldExpression) { if exp.AfterField != nil { exp.AfterField.Accept(visitor) } }
[ "func", "(", "visitor", "*", "findEntityVisitor", ")", "VisitFieldExpression", "(", "exp", "*", "sql", ".", "FieldExpression", ")", "{", "if", "exp", ".", "AfterField", "!=", "nil", "{", "exp", ".", "AfterField", ".", "Accept", "(", "visitor", ")", "\n", ...
// VisitFieldExpression just propagates to AfterFieldExpression
[ "VisitFieldExpression", "just", "propagates", "to", "AfterFieldExpression" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/cassandra/query.go#L305-L309
4,407
ligato/cn-infra
examples/cassandra-lib/main.go
MarshalCQL
func (w *Wrapper01) MarshalCQL(info gocql.TypeInfo) ([]byte, error) { if w.ip == nil { return []byte{}, nil } return []byte(w.ip.String()), nil }
go
func (w *Wrapper01) MarshalCQL(info gocql.TypeInfo) ([]byte, error) { if w.ip == nil { return []byte{}, nil } return []byte(w.ip.String()), nil }
[ "func", "(", "w", "*", "Wrapper01", ")", "MarshalCQL", "(", "info", "gocql", ".", "TypeInfo", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "w", ".", "ip", "==", "nil", "{", "return", "[", "]", "byte", "{", "}", ",", "nil", "\n", ...
// MarshalCQL serializes the string representation of net.IPNet
[ "MarshalCQL", "serializes", "the", "string", "representation", "of", "net", ".", "IPNet" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/cassandra-lib/main.go#L234-L241
4,408
ligato/cn-infra
examples/cassandra-lib/main.go
UnmarshalCQL
func (w *Wrapper01) UnmarshalCQL(info gocql.TypeInfo, data []byte) error { if len(data) > 0 { _, ipPrefix, err := net.ParseCIDR(string(data)) if err != nil { return err } w.ip = ipPrefix } return nil }
go
func (w *Wrapper01) UnmarshalCQL(info gocql.TypeInfo, data []byte) error { if len(data) > 0 { _, ipPrefix, err := net.ParseCIDR(string(data)) if err != nil { return err } w.ip = ipPrefix } return nil }
[ "func", "(", "w", "*", "Wrapper01", ")", "UnmarshalCQL", "(", "info", "gocql", ".", "TypeInfo", ",", "data", "[", "]", "byte", ")", "error", "{", "if", "len", "(", "data", ")", ">", "0", "{", "_", ",", "ipPrefix", ",", "err", ":=", "net", ".", ...
// UnmarshalCQL deserializes the string representation of net.IPNet
[ "UnmarshalCQL", "deserializes", "the", "string", "representation", "of", "net", ".", "IPNet" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/cassandra-lib/main.go#L244-L256
4,409
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
NewEtcdConnectionWithBytes
func NewEtcdConnectionWithBytes(config ClientConfig, log logging.Logger) (*BytesConnectionEtcd, error) { t := time.Now() l := log.WithField("endpoints", config.Endpoints) l.Debugf("Connecting to Etcd..") etcdClient, err := clientv3.New(*config.Config) if err != nil { l.Warnf("Failed to connect to Etcd: %v", err) return nil, err } l.Infof("Connected to Etcd (took %v)", time.Since(t)) conn, err := NewEtcdConnectionUsingClient(etcdClient, log) if err != nil { return nil, err } conn.opTimeout = config.OpTimeout return conn, nil }
go
func NewEtcdConnectionWithBytes(config ClientConfig, log logging.Logger) (*BytesConnectionEtcd, error) { t := time.Now() l := log.WithField("endpoints", config.Endpoints) l.Debugf("Connecting to Etcd..") etcdClient, err := clientv3.New(*config.Config) if err != nil { l.Warnf("Failed to connect to Etcd: %v", err) return nil, err } l.Infof("Connected to Etcd (took %v)", time.Since(t)) conn, err := NewEtcdConnectionUsingClient(etcdClient, log) if err != nil { return nil, err } conn.opTimeout = config.OpTimeout return conn, nil }
[ "func", "NewEtcdConnectionWithBytes", "(", "config", "ClientConfig", ",", "log", "logging", ".", "Logger", ")", "(", "*", "BytesConnectionEtcd", ",", "error", ")", "{", "t", ":=", "time", ".", "Now", "(", ")", "\n\n", "l", ":=", "log", ".", "WithField", ...
// NewEtcdConnectionWithBytes creates new connection to etcd based on the given // config file.
[ "NewEtcdConnectionWithBytes", "creates", "new", "connection", "to", "etcd", "based", "on", "the", "given", "config", "file", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L54-L75
4,410
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
NewEtcdConnectionUsingClient
func NewEtcdConnectionUsingClient(etcdClient *clientv3.Client, log logging.Logger) (*BytesConnectionEtcd, error) { conn := BytesConnectionEtcd{ Logger: log, etcdClient: etcdClient, lessor: clientv3.NewLease(etcdClient), opTimeout: defaultOpTimeout, } return &conn, nil }
go
func NewEtcdConnectionUsingClient(etcdClient *clientv3.Client, log logging.Logger) (*BytesConnectionEtcd, error) { conn := BytesConnectionEtcd{ Logger: log, etcdClient: etcdClient, lessor: clientv3.NewLease(etcdClient), opTimeout: defaultOpTimeout, } return &conn, nil }
[ "func", "NewEtcdConnectionUsingClient", "(", "etcdClient", "*", "clientv3", ".", "Client", ",", "log", "logging", ".", "Logger", ")", "(", "*", "BytesConnectionEtcd", ",", "error", ")", "{", "conn", ":=", "BytesConnectionEtcd", "{", "Logger", ":", "log", ",", ...
// NewEtcdConnectionUsingClient creates a new instance of BytesConnectionEtcd // using the provided etcd client. // This constructor is used primarily for testing.
[ "NewEtcdConnectionUsingClient", "creates", "a", "new", "instance", "of", "BytesConnectionEtcd", "using", "the", "provided", "etcd", "client", ".", "This", "constructor", "is", "used", "primarily", "for", "testing", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L80-L88
4,411
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
Close
func (db *BytesConnectionEtcd) Close() error { if db.etcdClient != nil { return db.etcdClient.Close() } return nil }
go
func (db *BytesConnectionEtcd) Close() error { if db.etcdClient != nil { return db.etcdClient.Close() } return nil }
[ "func", "(", "db", "*", "BytesConnectionEtcd", ")", "Close", "(", ")", "error", "{", "if", "db", ".", "etcdClient", "!=", "nil", "{", "return", "db", ".", "etcdClient", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close closes the connection to ETCD.
[ "Close", "closes", "the", "connection", "to", "ETCD", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L91-L96
4,412
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
Put
func (pdb *BytesBrokerWatcherEtcd) Put(key string, data []byte, opts ...datasync.PutOption) error { return putInternal(pdb.Logger, pdb.kv, pdb.lessor, pdb.opTimeout, key, data, opts...) }
go
func (pdb *BytesBrokerWatcherEtcd) Put(key string, data []byte, opts ...datasync.PutOption) error { return putInternal(pdb.Logger, pdb.kv, pdb.lessor, pdb.opTimeout, key, data, opts...) }
[ "func", "(", "pdb", "*", "BytesBrokerWatcherEtcd", ")", "Put", "(", "key", "string", ",", "data", "[", "]", "byte", ",", "opts", "...", "datasync", ".", "PutOption", ")", "error", "{", "return", "putInternal", "(", "pdb", ".", "Logger", ",", "pdb", "."...
// Put calls 'Put' function of the underlying BytesConnectionEtcd. // KeyPrefix defined in constructor is prepended to the key argument.
[ "Put", "calls", "Put", "function", "of", "the", "underlying", "BytesConnectionEtcd", ".", "KeyPrefix", "defined", "in", "constructor", "is", "prepended", "to", "the", "key", "argument", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L130-L132
4,413
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
GetValue
func (pdb *BytesBrokerWatcherEtcd) GetValue(key string) (data []byte, found bool, revision int64, err error) { return getValueInternal(pdb.Logger, pdb.kv, pdb.opTimeout, key) }
go
func (pdb *BytesBrokerWatcherEtcd) GetValue(key string) (data []byte, found bool, revision int64, err error) { return getValueInternal(pdb.Logger, pdb.kv, pdb.opTimeout, key) }
[ "func", "(", "pdb", "*", "BytesBrokerWatcherEtcd", ")", "GetValue", "(", "key", "string", ")", "(", "data", "[", "]", "byte", ",", "found", "bool", ",", "revision", "int64", ",", "err", "error", ")", "{", "return", "getValueInternal", "(", "pdb", ".", ...
// GetValue calls 'GetValue' function of the underlying BytesConnectionEtcd. // KeyPrefix defined in constructor is prepended to the key argument.
[ "GetValue", "calls", "GetValue", "function", "of", "the", "underlying", "BytesConnectionEtcd", ".", "KeyPrefix", "defined", "in", "constructor", "is", "prepended", "to", "the", "key", "argument", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L143-L145
4,414
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
Delete
func (pdb *BytesBrokerWatcherEtcd) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) { return deleteInternal(pdb.Logger, pdb.kv, pdb.opTimeout, key, opts...) }
go
func (pdb *BytesBrokerWatcherEtcd) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) { return deleteInternal(pdb.Logger, pdb.kv, pdb.opTimeout, key, opts...) }
[ "func", "(", "pdb", "*", "BytesBrokerWatcherEtcd", ")", "Delete", "(", "key", "string", ",", "opts", "...", "datasync", ".", "DelOption", ")", "(", "existed", "bool", ",", "err", "error", ")", "{", "return", "deleteInternal", "(", "pdb", ".", "Logger", "...
// Delete calls 'Delete' function of the underlying BytesConnectionEtcd. // KeyPrefix defined in constructor is prepended to the key argument.
[ "Delete", "calls", "Delete", "function", "of", "the", "underlying", "BytesConnectionEtcd", ".", "KeyPrefix", "defined", "in", "constructor", "is", "prepended", "to", "the", "key", "argument", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L162-L164
4,415
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
watchInternal
func watchInternal(log logging.Logger, watcher clientv3.Watcher, closeCh chan string, prefix string, resp func(keyval.BytesWatchResp)) error { ctx, cancel := context.WithCancel(context.Background()) recvChan := watcher.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithPrevKV()) go func(registeredKey string) { var compactRev int64 for { select { case wresp, ok := <-recvChan: if !ok { log.WithField("prefix", prefix).Warn("Watch recv channel was closed") if compactRev != 0 { recvChan = watcher.Watch(context.Background(), prefix, clientv3.WithPrefix(), clientv3.WithPrevKV(), clientv3.WithRev(compactRev)) log.WithFields(logging.Fields{ "prefix": prefix, "rev": compactRev, }).Warn("Watch recv channel was re-created") compactRev = 0 continue } return } if wresp.Canceled { log.WithField("prefix", prefix).Warn("Watch was canceled") } err := wresp.Err() if err != nil { log.WithFields(logging.Fields{ "prefix": prefix, "err": err, }).Warn("Watch returned error") } compactRev = wresp.CompactRevision if compactRev != 0 { log.WithFields(logging.Fields{ "prefix": prefix, "rev": compactRev, }).Warn("Watched data were compacted ") } for _, ev := range wresp.Events { handleWatchEvent(log, resp, ev) } case closeVal, ok := <-closeCh: if !ok || closeVal == registeredKey { cancel() log.WithField("prefix", prefix).Debug("Watch ended") return } } } }(prefix) return nil }
go
func watchInternal(log logging.Logger, watcher clientv3.Watcher, closeCh chan string, prefix string, resp func(keyval.BytesWatchResp)) error { ctx, cancel := context.WithCancel(context.Background()) recvChan := watcher.Watch(ctx, prefix, clientv3.WithPrefix(), clientv3.WithPrevKV()) go func(registeredKey string) { var compactRev int64 for { select { case wresp, ok := <-recvChan: if !ok { log.WithField("prefix", prefix).Warn("Watch recv channel was closed") if compactRev != 0 { recvChan = watcher.Watch(context.Background(), prefix, clientv3.WithPrefix(), clientv3.WithPrevKV(), clientv3.WithRev(compactRev)) log.WithFields(logging.Fields{ "prefix": prefix, "rev": compactRev, }).Warn("Watch recv channel was re-created") compactRev = 0 continue } return } if wresp.Canceled { log.WithField("prefix", prefix).Warn("Watch was canceled") } err := wresp.Err() if err != nil { log.WithFields(logging.Fields{ "prefix": prefix, "err": err, }).Warn("Watch returned error") } compactRev = wresp.CompactRevision if compactRev != 0 { log.WithFields(logging.Fields{ "prefix": prefix, "rev": compactRev, }).Warn("Watched data were compacted ") } for _, ev := range wresp.Events { handleWatchEvent(log, resp, ev) } case closeVal, ok := <-closeCh: if !ok || closeVal == registeredKey { cancel() log.WithField("prefix", prefix).Debug("Watch ended") return } } } }(prefix) return nil }
[ "func", "watchInternal", "(", "log", "logging", ".", "Logger", ",", "watcher", "clientv3", ".", "Watcher", ",", "closeCh", "chan", "string", ",", "prefix", "string", ",", "resp", "func", "(", "keyval", ".", "BytesWatchResp", ")", ")", "error", "{", "ctx", ...
// watchInternal starts the watch subscription for the key.
[ "watchInternal", "starts", "the", "watch", "subscription", "for", "the", "key", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L225-L280
4,416
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
Put
func (db *BytesConnectionEtcd) Put(key string, binData []byte, opts ...datasync.PutOption) error { return putInternal(db.Logger, db.etcdClient, db.lessor, db.opTimeout, key, binData, opts...) }
go
func (db *BytesConnectionEtcd) Put(key string, binData []byte, opts ...datasync.PutOption) error { return putInternal(db.Logger, db.etcdClient, db.lessor, db.opTimeout, key, binData, opts...) }
[ "func", "(", "db", "*", "BytesConnectionEtcd", ")", "Put", "(", "key", "string", ",", "binData", "[", "]", "byte", ",", "opts", "...", "datasync", ".", "PutOption", ")", "error", "{", "return", "putInternal", "(", "db", ".", "Logger", ",", "db", ".", ...
// Put writes the provided key-value item into the data store. // Returns an error if the item could not be written, nil otherwise.
[ "Put", "writes", "the", "provided", "key", "-", "value", "item", "into", "the", "data", "store", ".", "Returns", "an", "error", "if", "the", "item", "could", "not", "be", "written", "nil", "otherwise", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L284-L286
4,417
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
ListValuesRange
func (db *BytesConnectionEtcd) ListValuesRange(fromPrefix string, toPrefix string) (keyval.BytesKeyValIterator, error) { return listValuesRangeInternal(db.Logger, db.etcdClient, db.opTimeout, fromPrefix, toPrefix) }
go
func (db *BytesConnectionEtcd) ListValuesRange(fromPrefix string, toPrefix string) (keyval.BytesKeyValIterator, error) { return listValuesRangeInternal(db.Logger, db.etcdClient, db.opTimeout, fromPrefix, toPrefix) }
[ "func", "(", "db", "*", "BytesConnectionEtcd", ")", "ListValuesRange", "(", "fromPrefix", "string", ",", "toPrefix", "string", ")", "(", "keyval", ".", "BytesKeyValIterator", ",", "error", ")", "{", "return", "listValuesRangeInternal", "(", "db", ".", "Logger", ...
// ListValuesRange returns an iterator that enables traversing values stored // under the keys from a given range.
[ "ListValuesRange", "returns", "an", "iterator", "that", "enables", "traversing", "values", "stored", "under", "the", "keys", "from", "a", "given", "range", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L455-L457
4,418
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
Compact
func (db *BytesConnectionEtcd) Compact(rev ...int64) (int64, error) { return compactInternal(db.Logger, db.etcdClient, db.opTimeout, rev...) }
go
func (db *BytesConnectionEtcd) Compact(rev ...int64) (int64, error) { return compactInternal(db.Logger, db.etcdClient, db.opTimeout, rev...) }
[ "func", "(", "db", "*", "BytesConnectionEtcd", ")", "Compact", "(", "rev", "...", "int64", ")", "(", "int64", ",", "error", ")", "{", "return", "compactInternal", "(", "db", ".", "Logger", ",", "db", ".", "etcdClient", ",", "db", ".", "opTimeout", ",",...
// Compact compacts the ETCD database to specific revision
[ "Compact", "compacts", "the", "ETCD", "database", "to", "specific", "revision" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L475-L477
4,419
ligato/cn-infra
db/keyval/etcd/bytes_broker_impl.go
GetRevision
func (db *BytesConnectionEtcd) GetRevision() (revision int64, err error) { return getRevisionInternal(db.Logger, db.etcdClient, db.opTimeout) }
go
func (db *BytesConnectionEtcd) GetRevision() (revision int64, err error) { return getRevisionInternal(db.Logger, db.etcdClient, db.opTimeout) }
[ "func", "(", "db", "*", "BytesConnectionEtcd", ")", "GetRevision", "(", ")", "(", "revision", "int64", ",", "err", "error", ")", "{", "return", "getRevisionInternal", "(", "db", ".", "Logger", ",", "db", ".", "etcdClient", ",", "db", ".", "opTimeout", ")...
// GetRevision returns current revision of ETCD database
[ "GetRevision", "returns", "current", "revision", "of", "ETCD", "database" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/etcd/bytes_broker_impl.go#L508-L510
4,420
ligato/cn-infra
datasync/syncbase/done.go
Done
func (ev *DoneChannel) Done(err error) { if ev.DoneChan != nil { select { case ev.DoneChan <- err: // sent successfully default: logrus.DefaultLogger().Debug("Nobody is listening anymore") } } else if err != nil { logrus.DefaultLogger().Error(err) } }
go
func (ev *DoneChannel) Done(err error) { if ev.DoneChan != nil { select { case ev.DoneChan <- err: // sent successfully default: logrus.DefaultLogger().Debug("Nobody is listening anymore") } } else if err != nil { logrus.DefaultLogger().Error(err) } }
[ "func", "(", "ev", "*", "DoneChannel", ")", "Done", "(", "err", "error", ")", "{", "if", "ev", ".", "DoneChan", "!=", "nil", "{", "select", "{", "case", "ev", ".", "DoneChan", "<-", "err", ":", "// sent successfully", "default", ":", "logrus", ".", "...
// Done propagates error to the channel.
[ "Done", "propagates", "error", "to", "the", "channel", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/done.go#L31-L42
4,421
ligato/cn-infra
datasync/syncbase/done.go
Done
func (ev *DoneCallback) Done(err error) { if ev.Callback != nil { ev.Callback(err) } else if err != nil { logrus.DefaultLogger().Error(err) } }
go
func (ev *DoneCallback) Done(err error) { if ev.Callback != nil { ev.Callback(err) } else if err != nil { logrus.DefaultLogger().Error(err) } }
[ "func", "(", "ev", "*", "DoneCallback", ")", "Done", "(", "err", "error", ")", "{", "if", "ev", ".", "Callback", "!=", "nil", "{", "ev", ".", "Callback", "(", "err", ")", "\n", "}", "else", "if", "err", "!=", "nil", "{", "logrus", ".", "DefaultLo...
// Done propagates error to the callback.
[ "Done", "propagates", "error", "to", "the", "callback", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/done.go#L51-L57
4,422
ligato/cn-infra
datasync/syncbase/done.go
AggregateDone
func AggregateDone(events []func(chan error), done chan error) { partialDone := make(chan error, 5) go collectDoneEvents(partialDone, done, len(events)) for _, event := range events { event(partialDone) // fire event } }
go
func AggregateDone(events []func(chan error), done chan error) { partialDone := make(chan error, 5) go collectDoneEvents(partialDone, done, len(events)) for _, event := range events { event(partialDone) // fire event } }
[ "func", "AggregateDone", "(", "events", "[", "]", "func", "(", "chan", "error", ")", ",", "done", "chan", "error", ")", "{", "partialDone", ":=", "make", "(", "chan", "error", ",", "5", ")", "\n\n", "go", "collectDoneEvents", "(", "partialDone", ",", "...
// AggregateDone can be reused to avoid repetitive code that triggers a slice of events and waits until it is finished.
[ "AggregateDone", "can", "be", "reused", "to", "avoid", "repetitive", "code", "that", "triggers", "a", "slice", "of", "events", "and", "waits", "until", "it", "is", "finished", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/done.go#L60-L68
4,423
ligato/cn-infra
db/keyval/redis/bytes_watcher_impl.go
NewBytesWatchPutResp
func NewBytesWatchPutResp(key string, value []byte, prevValue []byte, revision int64) *BytesWatchPutResp { return &BytesWatchPutResp{key: key, value: value, prevValue: prevValue, rev: revision} }
go
func NewBytesWatchPutResp(key string, value []byte, prevValue []byte, revision int64) *BytesWatchPutResp { return &BytesWatchPutResp{key: key, value: value, prevValue: prevValue, rev: revision} }
[ "func", "NewBytesWatchPutResp", "(", "key", "string", ",", "value", "[", "]", "byte", ",", "prevValue", "[", "]", "byte", ",", "revision", "int64", ")", "*", "BytesWatchPutResp", "{", "return", "&", "BytesWatchPutResp", "{", "key", ":", "key", ",", "value"...
// NewBytesWatchPutResp creates an instance of BytesWatchPutResp.
[ "NewBytesWatchPutResp", "creates", "an", "instance", "of", "BytesWatchPutResp", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/redis/bytes_watcher_impl.go#L38-L40
4,424
ligato/cn-infra
db/keyval/redis/bytes_watcher_impl.go
Watch
func (db *BytesConnectionRedis) Watch(resp func(keyval.BytesWatchResp), closeChan chan string, keys ...string) error { if db.closed { return fmt.Errorf("watch(%v) called on a closed connection", keys) } db.closeCh = closeChan return watch(db, resp, db.closeCh, nil, nil, keys...) }
go
func (db *BytesConnectionRedis) Watch(resp func(keyval.BytesWatchResp), closeChan chan string, keys ...string) error { if db.closed { return fmt.Errorf("watch(%v) called on a closed connection", keys) } db.closeCh = closeChan return watch(db, resp, db.closeCh, nil, nil, keys...) }
[ "func", "(", "db", "*", "BytesConnectionRedis", ")", "Watch", "(", "resp", "func", "(", "keyval", ".", "BytesWatchResp", ")", ",", "closeChan", "chan", "string", ",", "keys", "...", "string", ")", "error", "{", "if", "db", ".", "closed", "{", "return", ...
// Watch starts subscription for changes associated with the selected key. Watch events will be delivered to respChan. // Subscription can be canceled by StopWatch call.
[ "Watch", "starts", "subscription", "for", "changes", "associated", "with", "the", "selected", "key", ".", "Watch", "events", "will", "be", "delivered", "to", "respChan", ".", "Subscription", "can", "be", "canceled", "by", "StopWatch", "call", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/redis/bytes_watcher_impl.go#L105-L112
4,425
ligato/cn-infra
db/keyval/redis/bytes_watcher_impl.go
Watch
func (pdb *BytesBrokerWatcherRedis) Watch(resp func(keyval.BytesWatchResp), closeChan chan string, keys ...string) error { if pdb.delegate.closed { return fmt.Errorf("watch(%v) called on a closed connection", keys) } return watch(pdb.delegate, resp, closeChan, pdb.addPrefix, pdb.trimPrefix, keys...) }
go
func (pdb *BytesBrokerWatcherRedis) Watch(resp func(keyval.BytesWatchResp), closeChan chan string, keys ...string) error { if pdb.delegate.closed { return fmt.Errorf("watch(%v) called on a closed connection", keys) } return watch(pdb.delegate, resp, closeChan, pdb.addPrefix, pdb.trimPrefix, keys...) }
[ "func", "(", "pdb", "*", "BytesBrokerWatcherRedis", ")", "Watch", "(", "resp", "func", "(", "keyval", ".", "BytesWatchResp", ")", ",", "closeChan", "chan", "string", ",", "keys", "...", "string", ")", "error", "{", "if", "pdb", ".", "delegate", ".", "clo...
// Watch starts subscription for changes associated with the selected key. Watch events will be delivered to respChan.
[ "Watch", "starts", "subscription", "for", "changes", "associated", "with", "the", "selected", "key", ".", "Watch", "events", "will", "be", "delivered", "to", "respChan", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/redis/bytes_watcher_impl.go#L193-L198
4,426
ligato/cn-infra
datasync/msgsync/options.go
UseMessaging
func UseMessaging(m messaging.Mux) Option { return func(p *Plugin) { p.Deps.Messaging = m } }
go
func UseMessaging(m messaging.Mux) Option { return func(p *Plugin) { p.Deps.Messaging = m } }
[ "func", "UseMessaging", "(", "m", "messaging", ".", "Mux", ")", "Option", "{", "return", "func", "(", "p", "*", "Plugin", ")", "{", "p", ".", "Deps", ".", "Messaging", "=", "m", "\n", "}", "\n", "}" ]
// UseMessaging returns Option that sets Messaging.
[ "UseMessaging", "returns", "Option", "that", "sets", "Messaging", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/msgsync/options.go#L54-L58
4,427
ligato/cn-infra
utils/addrs/ip.go
Swap
func (arr SortedIPs) Swap(i, j int) { arr[i], arr[j] = arr[j], arr[i] }
go
func (arr SortedIPs) Swap(i, j int) { arr[i], arr[j] = arr[j], arr[i] }
[ "func", "(", "arr", "SortedIPs", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "arr", "[", "i", "]", ",", "arr", "[", "j", "]", "=", "arr", "[", "j", "]", ",", "arr", "[", "i", "]", "\n", "}" ]
// Swap swaps two items in slice identified by indexes // Implements sort.Interface
[ "Swap", "swaps", "two", "items", "in", "slice", "identified", "by", "indexes", "Implements", "sort", ".", "Interface" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/utils/addrs/ip.go#L22-L24
4,428
ligato/cn-infra
utils/addrs/ip.go
Less
func (arr SortedIPs) Less(i, j int) bool { return lessAdrr(arr[i], arr[j]) }
go
func (arr SortedIPs) Less(i, j int) bool { return lessAdrr(arr[i], arr[j]) }
[ "func", "(", "arr", "SortedIPs", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "lessAdrr", "(", "arr", "[", "i", "]", ",", "arr", "[", "j", "]", ")", "\n", "}" ]
// Less returns true if the item in slice at index i in slice // should be sorted before the element with index j // Implements sort.Interface
[ "Less", "returns", "true", "if", "the", "item", "in", "slice", "at", "index", "i", "in", "slice", "should", "be", "sorted", "before", "the", "element", "with", "index", "j", "Implements", "sort", ".", "Interface" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/utils/addrs/ip.go#L29-L31
4,429
ligato/cn-infra
utils/addrs/ip.go
DiffAddr
func DiffAddr(newConfig []*net.IPNet, oldConfig []*net.IPNet) (toBeDeleted []*net.IPNet, toBeAdded []*net.IPNet) { var add []*net.IPNet var del []*net.IPNet //sort n := SortedIPs(newConfig) sort.Sort(&n) o := SortedIPs(oldConfig) sort.Sort(&o) //compare i := 0 j := 0 for i < len(n) && j < len(o) { if eqAddr(n[i], o[j]) { i++ j++ } else { if lessAdrr(n[i], o[j]) { add = append(add, n[i]) i++ } else { del = append(del, o[j]) j++ } } } for ; i < len(n); i++ { add = append(add, n[i]) } for ; j < len(o); j++ { del = append(del, o[j]) } return del, add }
go
func DiffAddr(newConfig []*net.IPNet, oldConfig []*net.IPNet) (toBeDeleted []*net.IPNet, toBeAdded []*net.IPNet) { var add []*net.IPNet var del []*net.IPNet //sort n := SortedIPs(newConfig) sort.Sort(&n) o := SortedIPs(oldConfig) sort.Sort(&o) //compare i := 0 j := 0 for i < len(n) && j < len(o) { if eqAddr(n[i], o[j]) { i++ j++ } else { if lessAdrr(n[i], o[j]) { add = append(add, n[i]) i++ } else { del = append(del, o[j]) j++ } } } for ; i < len(n); i++ { add = append(add, n[i]) } for ; j < len(o); j++ { del = append(del, o[j]) } return del, add }
[ "func", "DiffAddr", "(", "newConfig", "[", "]", "*", "net", ".", "IPNet", ",", "oldConfig", "[", "]", "*", "net", ".", "IPNet", ")", "(", "toBeDeleted", "[", "]", "*", "net", ".", "IPNet", ",", "toBeAdded", "[", "]", "*", "net", ".", "IPNet", ")"...
// DiffAddr calculates the difference between two slices of AddrWithPrefix configuration. // Returns a list of addresses that should be deleted and added to the current configuration to match newConfig.
[ "DiffAddr", "calculates", "the", "difference", "between", "two", "slices", "of", "AddrWithPrefix", "configuration", ".", "Returns", "a", "list", "of", "addresses", "that", "should", "be", "deleted", "and", "added", "to", "the", "current", "configuration", "to", ...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/utils/addrs/ip.go#L47-L82
4,430
ligato/cn-infra
utils/addrs/ip.go
StrAddrsToStruct
func StrAddrsToStruct(addrs []string) ([]*net.IPNet, error) { var result []*net.IPNet for _, addressWithPrefix := range addrs { if addressWithPrefix == "" { continue } parsedIPWithPrefix, _, err := ParseIPWithPrefix(addressWithPrefix) if err != nil { return result, err } result = append(result, parsedIPWithPrefix) } return result, nil }
go
func StrAddrsToStruct(addrs []string) ([]*net.IPNet, error) { var result []*net.IPNet for _, addressWithPrefix := range addrs { if addressWithPrefix == "" { continue } parsedIPWithPrefix, _, err := ParseIPWithPrefix(addressWithPrefix) if err != nil { return result, err } result = append(result, parsedIPWithPrefix) } return result, nil }
[ "func", "StrAddrsToStruct", "(", "addrs", "[", "]", "string", ")", "(", "[", "]", "*", "net", ".", "IPNet", ",", "error", ")", "{", "var", "result", "[", "]", "*", "net", ".", "IPNet", "\n", "for", "_", ",", "addressWithPrefix", ":=", "range", "add...
// StrAddrsToStruct converts slice of strings representing ipv4 addresses to IPNet structures
[ "StrAddrsToStruct", "converts", "slice", "of", "strings", "representing", "ipv4", "addresses", "to", "IPNet", "structures" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/utils/addrs/ip.go#L85-L99
4,431
ligato/cn-infra
utils/addrs/ip.go
IsIPv6
func IsIPv6(addr string) (bool, error) { ip := net.ParseIP(addr) if ip == nil { return false, fmt.Errorf("invalid IP address: %q", addr) } return ip.To4() == nil, nil }
go
func IsIPv6(addr string) (bool, error) { ip := net.ParseIP(addr) if ip == nil { return false, fmt.Errorf("invalid IP address: %q", addr) } return ip.To4() == nil, nil }
[ "func", "IsIPv6", "(", "addr", "string", ")", "(", "bool", ",", "error", ")", "{", "ip", ":=", "net", ".", "ParseIP", "(", "addr", ")", "\n", "if", "ip", "==", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "add...
// IsIPv6 returns true if provided IP address is IPv6, false otherwise
[ "IsIPv6", "returns", "true", "if", "provided", "IP", "address", "is", "IPv6", "false", "otherwise" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/utils/addrs/ip.go#L140-L146
4,432
ligato/cn-infra
examples/kafka-lib/utils/prompter.go
GetCommand
func GetCommand() *Command { var command *Command loop: for { cmd := prompter.Choose("\nEnter command", []string{"quit", "message"}, "message") command = new(Command) switch cmd { case "quit": command.Cmd = "quit" fin := prompter.YN("Quit?", true) if fin { break loop } case "message": command.Cmd = "message" var ( topic string text string ) for { topic = prompter.Prompt("Enter topic (REQUIRED)", "") if topic == "" { fmt.Println("topic cannot be blank") } else { break } } for { text = prompter.Prompt("Enter message (REQUIRED)", "") if text == "" { fmt.Println("message cannot be blank") } else { break } } command.Topic = topic command.Text = text key := prompter.Prompt("Enter key", "") command.Key = key metadata := prompter.Prompt("Enter metadata", "") command.Metadata = metadata send := prompter.YN("Send Message?", true) if send { break loop } } } return command }
go
func GetCommand() *Command { var command *Command loop: for { cmd := prompter.Choose("\nEnter command", []string{"quit", "message"}, "message") command = new(Command) switch cmd { case "quit": command.Cmd = "quit" fin := prompter.YN("Quit?", true) if fin { break loop } case "message": command.Cmd = "message" var ( topic string text string ) for { topic = prompter.Prompt("Enter topic (REQUIRED)", "") if topic == "" { fmt.Println("topic cannot be blank") } else { break } } for { text = prompter.Prompt("Enter message (REQUIRED)", "") if text == "" { fmt.Println("message cannot be blank") } else { break } } command.Topic = topic command.Text = text key := prompter.Prompt("Enter key", "") command.Key = key metadata := prompter.Prompt("Enter metadata", "") command.Metadata = metadata send := prompter.YN("Send Message?", true) if send { break loop } } } return command }
[ "func", "GetCommand", "(", ")", "*", "Command", "{", "var", "command", "*", "Command", "\n", "loop", ":", "for", "{", "cmd", ":=", "prompter", ".", "Choose", "(", "\"", "\\n", "\"", ",", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", ...
// GetCommand allows user to select a command and reads the input arguments.
[ "GetCommand", "allows", "user", "to", "select", "a", "command", "and", "reads", "the", "input", "arguments", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/kafka-lib/utils/prompter.go#L38-L86
4,433
ligato/cn-infra
db/keyval/filedb/decoder/decoder_yaml.go
Encode
func (yd *YAMLDecoder) Encode(data []*FileDataEntry) ([]byte, error) { // Convert to json-specific structure var yamlFileEntries []yamlFileEntry for _, dataEntry := range data { yamlFileEntries = append(yamlFileEntries, yamlFileEntry{ Key: dataEntry.Key, Value: dataEntry.Value, }) } // Encode to type specific structure yamlFile := &yamlFile{Data: yamlFileEntries} return yaml.Marshal(yamlFile) }
go
func (yd *YAMLDecoder) Encode(data []*FileDataEntry) ([]byte, error) { // Convert to json-specific structure var yamlFileEntries []yamlFileEntry for _, dataEntry := range data { yamlFileEntries = append(yamlFileEntries, yamlFileEntry{ Key: dataEntry.Key, Value: dataEntry.Value, }) } // Encode to type specific structure yamlFile := &yamlFile{Data: yamlFileEntries} return yaml.Marshal(yamlFile) }
[ "func", "(", "yd", "*", "YAMLDecoder", ")", "Encode", "(", "data", "[", "]", "*", "FileDataEntry", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Convert to json-specific structure", "var", "yamlFileEntries", "[", "]", "yamlFileEntry", "\n", "for", ...
// Encode provided file entries into json byte set
[ "Encode", "provided", "file", "entries", "into", "json", "byte", "set" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/decoder/decoder_yaml.go#L63-L75
4,434
ligato/cn-infra
db/keyval/filedb/decoder/decoder_yaml.go
Decode
func (yd *YAMLDecoder) Decode(byteSet []byte) ([]*FileDataEntry, error) { if len(byteSet) == 0 { return []*FileDataEntry{}, nil } // Decode to type-specific structure yamlFile := yamlFile{} err := yaml.Unmarshal(byteSet, &yamlFile) if err != nil { return nil, fmt.Errorf("failed to decode yaml file: %v", err) } // Convert to common file data entry list structure var dataEntries []*FileDataEntry for _, dataEntry := range yamlFile.Data { dataEntries = append(dataEntries, &FileDataEntry{Key: dataEntry.Key, Value: dataEntry.Value}) } return dataEntries, nil }
go
func (yd *YAMLDecoder) Decode(byteSet []byte) ([]*FileDataEntry, error) { if len(byteSet) == 0 { return []*FileDataEntry{}, nil } // Decode to type-specific structure yamlFile := yamlFile{} err := yaml.Unmarshal(byteSet, &yamlFile) if err != nil { return nil, fmt.Errorf("failed to decode yaml file: %v", err) } // Convert to common file data entry list structure var dataEntries []*FileDataEntry for _, dataEntry := range yamlFile.Data { dataEntries = append(dataEntries, &FileDataEntry{Key: dataEntry.Key, Value: dataEntry.Value}) } return dataEntries, nil }
[ "func", "(", "yd", "*", "YAMLDecoder", ")", "Decode", "(", "byteSet", "[", "]", "byte", ")", "(", "[", "]", "*", "FileDataEntry", ",", "error", ")", "{", "if", "len", "(", "byteSet", ")", "==", "0", "{", "return", "[", "]", "*", "FileDataEntry", ...
// Decode provided YAML file
[ "Decode", "provided", "YAML", "file" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/decoder/decoder_yaml.go#L78-L94
4,435
ligato/cn-infra
db/cryptodata/wrapper_proto.go
NewKvProtoPluginWrapper
func NewKvProtoPluginWrapper(kvp keyval.KvProtoPlugin, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *KvProtoPluginWrapper { return &KvProtoPluginWrapper{ KvProtoPlugin: kvp, decryptData: decryptData{ decryptFunc: decryptFunc, decrypter: decrypter, }, } }
go
func NewKvProtoPluginWrapper(kvp keyval.KvProtoPlugin, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *KvProtoPluginWrapper { return &KvProtoPluginWrapper{ KvProtoPlugin: kvp, decryptData: decryptData{ decryptFunc: decryptFunc, decrypter: decrypter, }, } }
[ "func", "NewKvProtoPluginWrapper", "(", "kvp", "keyval", ".", "KvProtoPlugin", ",", "decrypter", "ArbitraryDecrypter", ",", "decryptFunc", "DecryptFunc", ")", "*", "KvProtoPluginWrapper", "{", "return", "&", "KvProtoPluginWrapper", "{", "KvProtoPlugin", ":", "kvp", ",...
// NewKvProtoPluginWrapper creates wrapper for provided KvProtoPlugin, adding support for decrypting encrypted data
[ "NewKvProtoPluginWrapper", "creates", "wrapper", "for", "provided", "KvProtoPlugin", "adding", "support", "for", "decrypting", "encrypted", "data" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/wrapper_proto.go#L60-L68
4,436
ligato/cn-infra
db/cryptodata/wrapper_proto.go
NewProtoBrokerWrapper
func NewProtoBrokerWrapper(pb keyval.ProtoBroker, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *ProtoBrokerWrapper { return &ProtoBrokerWrapper{ ProtoBroker: pb, decryptData: decryptData{ decryptFunc: decryptFunc, decrypter: decrypter, }, } }
go
func NewProtoBrokerWrapper(pb keyval.ProtoBroker, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *ProtoBrokerWrapper { return &ProtoBrokerWrapper{ ProtoBroker: pb, decryptData: decryptData{ decryptFunc: decryptFunc, decrypter: decrypter, }, } }
[ "func", "NewProtoBrokerWrapper", "(", "pb", "keyval", ".", "ProtoBroker", ",", "decrypter", "ArbitraryDecrypter", ",", "decryptFunc", "DecryptFunc", ")", "*", "ProtoBrokerWrapper", "{", "return", "&", "ProtoBrokerWrapper", "{", "ProtoBroker", ":", "pb", ",", "decryp...
// NewProtoBrokerWrapper creates wrapper for provided ProtoBroker, adding support for decrypting encrypted data
[ "NewProtoBrokerWrapper", "creates", "wrapper", "for", "provided", "ProtoBroker", "adding", "support", "for", "decrypting", "encrypted", "data" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/wrapper_proto.go#L71-L79
4,437
ligato/cn-infra
db/cryptodata/wrapper_proto.go
NewProtoWatcherWrapper
func NewProtoWatcherWrapper(pb keyval.ProtoWatcher, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *ProtoWatcherWrapper { return &ProtoWatcherWrapper{ ProtoWatcher: pb, decryptData: decryptData{ decryptFunc: decryptFunc, decrypter: decrypter, }, } }
go
func NewProtoWatcherWrapper(pb keyval.ProtoWatcher, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *ProtoWatcherWrapper { return &ProtoWatcherWrapper{ ProtoWatcher: pb, decryptData: decryptData{ decryptFunc: decryptFunc, decrypter: decrypter, }, } }
[ "func", "NewProtoWatcherWrapper", "(", "pb", "keyval", ".", "ProtoWatcher", ",", "decrypter", "ArbitraryDecrypter", ",", "decryptFunc", "DecryptFunc", ")", "*", "ProtoWatcherWrapper", "{", "return", "&", "ProtoWatcherWrapper", "{", "ProtoWatcher", ":", "pb", ",", "d...
// NewProtoWatcherWrapper creates wrapper for provided ProtoWatcher, adding support for decrypting encrypted data
[ "NewProtoWatcherWrapper", "creates", "wrapper", "for", "provided", "ProtoWatcher", "adding", "support", "for", "decrypting", "encrypted", "data" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/wrapper_proto.go#L82-L90
4,438
ligato/cn-infra
logging/logrus/custom_formatter.go
Format
func (f *CustomFormatter) Format(entry *log.Entry) ([]byte, error) { buffer := &bytes.Buffer{} compulsoryFields := map[string]interface{}{} compulsoryFields[fieldKeyTime] = entry.Time.Format(time.RFC3339) compulsoryFields[fieldKeyMsg] = entry.Message compulsoryFields[fieldKeyLevel] = f.logLevelToString(entry.Level) if comp, found := entry.Data[fieldKeyComponent]; found { compulsoryFields[fieldKeyComponent] = fmt.Sprint(comp) } else { compulsoryFields[fieldKeyComponent] = "component" } compulsoryFields[fieldKeyProcess] = os.Getpid() // Print header (timestamp can be turned off) if f.ShowTimestamp { fmt.Fprint(buffer, compulsoryFields[fieldKeyTime]) buffer.WriteByte(' ') } for _, key := range compulsoryKeys[1:] { fmt.Fprint(buffer, compulsoryFields[key]) buffer.WriteByte(' ') } // Print explicit key-value pairs for k, v := range entry.Data { if !f.ignoredKey(k) { f.appendKeyValue(buffer, k, v) } } buffer.WriteString("message=") buffer.WriteByte('"') fmt.Fprint(buffer, compulsoryFields[fieldKeyMsg]) buffer.WriteByte('"') buffer.WriteByte('\n') return buffer.Bytes(), nil }
go
func (f *CustomFormatter) Format(entry *log.Entry) ([]byte, error) { buffer := &bytes.Buffer{} compulsoryFields := map[string]interface{}{} compulsoryFields[fieldKeyTime] = entry.Time.Format(time.RFC3339) compulsoryFields[fieldKeyMsg] = entry.Message compulsoryFields[fieldKeyLevel] = f.logLevelToString(entry.Level) if comp, found := entry.Data[fieldKeyComponent]; found { compulsoryFields[fieldKeyComponent] = fmt.Sprint(comp) } else { compulsoryFields[fieldKeyComponent] = "component" } compulsoryFields[fieldKeyProcess] = os.Getpid() // Print header (timestamp can be turned off) if f.ShowTimestamp { fmt.Fprint(buffer, compulsoryFields[fieldKeyTime]) buffer.WriteByte(' ') } for _, key := range compulsoryKeys[1:] { fmt.Fprint(buffer, compulsoryFields[key]) buffer.WriteByte(' ') } // Print explicit key-value pairs for k, v := range entry.Data { if !f.ignoredKey(k) { f.appendKeyValue(buffer, k, v) } } buffer.WriteString("message=") buffer.WriteByte('"') fmt.Fprint(buffer, compulsoryFields[fieldKeyMsg]) buffer.WriteByte('"') buffer.WriteByte('\n') return buffer.Bytes(), nil }
[ "func", "(", "f", "*", "CustomFormatter", ")", "Format", "(", "entry", "*", "log", ".", "Entry", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buffer", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "compulsoryFields", ":=", "map", "[", ...
// Format formats the given log entry.
[ "Format", "formats", "the", "given", "log", "entry", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/custom_formatter.go#L82-L121
4,439
ligato/cn-infra
health/probe/plugin_impl_probe.go
AfterInit
func (p *Plugin) AfterInit() error { if p.StatusCheck == nil { p.Log.Warnf("Unable to register probe handlers, StatusCheck is nil") return nil } if p.HTTP != nil { p.Log.Infof("Starting health http-probe on port %v", p.HTTP.GetPort()) p.HTTP.RegisterHTTPHandler(livenessProbePath, p.livenessProbeHandler, "GET") p.HTTP.RegisterHTTPHandler(readinessProbePath, p.readinessProbeHandler, "GET") } else { p.Log.Info("Unable to register http-probe handler, HTTP is nil") } if p.Prometheus != nil { if err := p.registerPrometheusProbe(); err != nil { return err } } else { p.Log.Info("Unable to register prometheus-probe handler, Prometheus is nil") } return nil }
go
func (p *Plugin) AfterInit() error { if p.StatusCheck == nil { p.Log.Warnf("Unable to register probe handlers, StatusCheck is nil") return nil } if p.HTTP != nil { p.Log.Infof("Starting health http-probe on port %v", p.HTTP.GetPort()) p.HTTP.RegisterHTTPHandler(livenessProbePath, p.livenessProbeHandler, "GET") p.HTTP.RegisterHTTPHandler(readinessProbePath, p.readinessProbeHandler, "GET") } else { p.Log.Info("Unable to register http-probe handler, HTTP is nil") } if p.Prometheus != nil { if err := p.registerPrometheusProbe(); err != nil { return err } } else { p.Log.Info("Unable to register prometheus-probe handler, Prometheus is nil") } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "AfterInit", "(", ")", "error", "{", "if", "p", ".", "StatusCheck", "==", "nil", "{", "p", ".", "Log", ".", "Warnf", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "if", "p", ".", "HTTP", ...
// AfterInit registers HTTP handlers for liveness and readiness probes.
[ "AfterInit", "registers", "HTTP", "handlers", "for", "liveness", "and", "readiness", "probes", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/probe/plugin_impl_probe.go#L67-L90
4,440
ligato/cn-infra
health/probe/plugin_impl_probe.go
readinessProbeHandler
func (p *Plugin) readinessProbeHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { ifStat := p.StatusCheck.GetInterfaceStats() agentStat := p.getAgentStatus() agentStat.InterfaceStats = &ifStat agentStatJSON, _ := json.Marshal(agentStat) if agentStat.State == status.OperationalState_OK { w.WriteHeader(http.StatusOK) } else { w.WriteHeader(http.StatusInternalServerError) } w.Write(agentStatJSON) } }
go
func (p *Plugin) readinessProbeHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { ifStat := p.StatusCheck.GetInterfaceStats() agentStat := p.getAgentStatus() agentStat.InterfaceStats = &ifStat agentStatJSON, _ := json.Marshal(agentStat) if agentStat.State == status.OperationalState_OK { w.WriteHeader(http.StatusOK) } else { w.WriteHeader(http.StatusInternalServerError) } w.Write(agentStatJSON) } }
[ "func", "(", "p", "*", "Plugin", ")", "readinessProbeHandler", "(", "formatter", "*", "render", ".", "Render", ")", "http", ".", "HandlerFunc", "{", "return", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", ...
// readinessProbeHandler handles k8s readiness probe.
[ "readinessProbeHandler", "handles", "k8s", "readiness", "probe", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/probe/plugin_impl_probe.go#L98-L111
4,441
ligato/cn-infra
health/probe/plugin_impl_probe.go
livenessProbeHandler
func (p *Plugin) livenessProbeHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { stat := p.getAgentStatus() statJSON, _ := json.Marshal(stat) if stat.State == status.OperationalState_INIT || stat.State == status.OperationalState_OK { w.WriteHeader(http.StatusOK) w.Write(statJSON) } else { w.WriteHeader(http.StatusInternalServerError) w.Write(statJSON) } } }
go
func (p *Plugin) livenessProbeHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { stat := p.getAgentStatus() statJSON, _ := json.Marshal(stat) if stat.State == status.OperationalState_INIT || stat.State == status.OperationalState_OK { w.WriteHeader(http.StatusOK) w.Write(statJSON) } else { w.WriteHeader(http.StatusInternalServerError) w.Write(statJSON) } } }
[ "func", "(", "p", "*", "Plugin", ")", "livenessProbeHandler", "(", "formatter", "*", "render", ".", "Render", ")", "http", ".", "HandlerFunc", "{", "return", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", ...
// livenessProbeHandler handles k8s liveness probe.
[ "livenessProbeHandler", "handles", "k8s", "liveness", "probe", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/probe/plugin_impl_probe.go#L114-L127
4,442
ligato/cn-infra
health/probe/plugin_impl_probe.go
getAgentStatus
func (p *Plugin) getAgentStatus() ExposedStatus { exposedStatus := ExposedStatus{ AgentStatus: p.StatusCheck.GetAgentStatus(), PluginStatus: p.StatusCheck.GetAllPluginStatus(), NonFatalPlugins: p.NonFatalPlugins, } // check whether error is caused by one of the plugins in NonFatalPlugin list if exposedStatus.AgentStatus.State == status.OperationalState_ERROR && len(p.NonFatalPlugins) > 0 { for k, v := range exposedStatus.PluginStatus { if v.State == status.OperationalState_ERROR { if isInSlice(p.NonFatalPlugins, k) { // treat error reported by this plugin as non fatal exposedStatus.AgentStatus.State = status.OperationalState_OK } else { exposedStatus.AgentStatus.State = status.OperationalState_ERROR break } } } } return exposedStatus }
go
func (p *Plugin) getAgentStatus() ExposedStatus { exposedStatus := ExposedStatus{ AgentStatus: p.StatusCheck.GetAgentStatus(), PluginStatus: p.StatusCheck.GetAllPluginStatus(), NonFatalPlugins: p.NonFatalPlugins, } // check whether error is caused by one of the plugins in NonFatalPlugin list if exposedStatus.AgentStatus.State == status.OperationalState_ERROR && len(p.NonFatalPlugins) > 0 { for k, v := range exposedStatus.PluginStatus { if v.State == status.OperationalState_ERROR { if isInSlice(p.NonFatalPlugins, k) { // treat error reported by this plugin as non fatal exposedStatus.AgentStatus.State = status.OperationalState_OK } else { exposedStatus.AgentStatus.State = status.OperationalState_ERROR break } } } } return exposedStatus }
[ "func", "(", "p", "*", "Plugin", ")", "getAgentStatus", "(", ")", "ExposedStatus", "{", "exposedStatus", ":=", "ExposedStatus", "{", "AgentStatus", ":", "p", ".", "StatusCheck", ".", "GetAgentStatus", "(", ")", ",", "PluginStatus", ":", "p", ".", "StatusChec...
// getAgentStatus return overall agent status + status of the plugins // the method takes into account non-fatal plugin settings
[ "getAgentStatus", "return", "overall", "agent", "status", "+", "status", "of", "the", "plugins", "the", "method", "takes", "into", "account", "non", "-", "fatal", "plugin", "settings" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/health/probe/plugin_impl_probe.go#L131-L156
4,443
ligato/cn-infra
examples/logs-lib/http/server.go
generateLogs
func generateLogs() { myLogger := logRegistry.NewLogger("MyLogger") for range time.NewTicker(10 * time.Second).C { myLogger.Debug("My logger") myLogger.Info("My logger") myLogger.Error("My logger") defaultLogger.Debug("Default logger") defaultLogger.Info("Default logger") defaultLogger.Error("Default logger") } }
go
func generateLogs() { myLogger := logRegistry.NewLogger("MyLogger") for range time.NewTicker(10 * time.Second).C { myLogger.Debug("My logger") myLogger.Info("My logger") myLogger.Error("My logger") defaultLogger.Debug("Default logger") defaultLogger.Info("Default logger") defaultLogger.Error("Default logger") } }
[ "func", "generateLogs", "(", ")", "{", "myLogger", ":=", "logRegistry", ".", "NewLogger", "(", "\"", "\"", ")", "\n\n", "for", "range", "time", ".", "NewTicker", "(", "10", "*", "time", ".", "Second", ")", ".", "C", "{", "myLogger", ".", "Debug", "("...
// Every 10 seconds prints a set of logs using default and custom logger
[ "Every", "10", "seconds", "prints", "a", "set", "of", "logs", "using", "default", "and", "custom", "logger" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/logs-lib/http/server.go#L34-L47
4,444
ligato/cn-infra
rpc/grpc/options.go
UseHTTP
func UseHTTP(h rest.HTTPHandlers) Option { return func(p *Plugin) { p.Deps.HTTP = h } }
go
func UseHTTP(h rest.HTTPHandlers) Option { return func(p *Plugin) { p.Deps.HTTP = h } }
[ "func", "UseHTTP", "(", "h", "rest", ".", "HTTPHandlers", ")", "Option", "{", "return", "func", "(", "p", "*", "Plugin", ")", "{", "p", ".", "Deps", ".", "HTTP", "=", "h", "\n", "}", "\n", "}" ]
// UseHTTP returns Option that sets HTTP handlers.
[ "UseHTTP", "returns", "Option", "that", "sets", "HTTP", "handlers", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/grpc/options.go#L72-L76
4,445
ligato/cn-infra
rpc/grpc/options.go
UseTLS
func UseTLS(c *tls.Config) Option { return func(p *Plugin) { p.tlsConfig = c } }
go
func UseTLS(c *tls.Config) Option { return func(p *Plugin) { p.tlsConfig = c } }
[ "func", "UseTLS", "(", "c", "*", "tls", ".", "Config", ")", "Option", "{", "return", "func", "(", "p", "*", "Plugin", ")", "{", "p", ".", "tlsConfig", "=", "c", "\n", "}", "\n", "}" ]
// UseTLS return Option that sets TLS config.
[ "UseTLS", "return", "Option", "that", "sets", "TLS", "config", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/grpc/options.go#L86-L90
4,446
ligato/cn-infra
rpc/rest/auth.go
newStaticAuthenticator
func newStaticAuthenticator(users []string) (*staticAuthenticator, error) { sa := &staticAuthenticator{ credentials: make(map[string]string), } for _, u := range users { fields := strings.Split(u, ":") if len(fields) != 2 { return nil, fmt.Errorf("invalid format of basic auth entry '%v' expected 'user:pass'", u) } sa.credentials[fields[0]] = fields[1] } return sa, nil }
go
func newStaticAuthenticator(users []string) (*staticAuthenticator, error) { sa := &staticAuthenticator{ credentials: make(map[string]string), } for _, u := range users { fields := strings.Split(u, ":") if len(fields) != 2 { return nil, fmt.Errorf("invalid format of basic auth entry '%v' expected 'user:pass'", u) } sa.credentials[fields[0]] = fields[1] } return sa, nil }
[ "func", "newStaticAuthenticator", "(", "users", "[", "]", "string", ")", "(", "*", "staticAuthenticator", ",", "error", ")", "{", "sa", ":=", "&", "staticAuthenticator", "{", "credentials", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", ...
// newStaticAuthenticator creates new instance of static authenticator. // Argument `users` is a slice of colon-separated username and password couples.
[ "newStaticAuthenticator", "creates", "new", "instance", "of", "static", "authenticator", ".", "Argument", "users", "is", "a", "slice", "of", "colon", "-", "separated", "username", "and", "password", "couples", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/auth.go#L42-L54
4,447
ligato/cn-infra
rpc/rest/auth.go
Authenticate
func (sa *staticAuthenticator) Authenticate(user string, pass string) bool { password, found := sa.credentials[user] if !found { return false } return pass == password }
go
func (sa *staticAuthenticator) Authenticate(user string, pass string) bool { password, found := sa.credentials[user] if !found { return false } return pass == password }
[ "func", "(", "sa", "*", "staticAuthenticator", ")", "Authenticate", "(", "user", "string", ",", "pass", "string", ")", "bool", "{", "password", ",", "found", ":=", "sa", ".", "credentials", "[", "user", "]", "\n", "if", "!", "found", "{", "return", "fa...
// Authenticate looks up the given user name and password in the internal map. // If match is found returns true, false otherwise.
[ "Authenticate", "looks", "up", "the", "given", "user", "name", "and", "password", "in", "the", "internal", "map", ".", "If", "match", "is", "found", "returns", "true", "false", "otherwise", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/auth.go#L58-L64
4,448
ligato/cn-infra
agent/agent.go
NewAgent
func NewAgent(opts ...Option) Agent { options := newOptions(opts...) if !flag.Parsed() { config.DefineDirFlag() for _, p := range options.Plugins { name := p.String() infraLogger.Debugf("registering flags for: %q", name) config.DefineFlagsFor(name) } flag.Parse() } return &agent{ opts: options, tracer: measure.NewTracer("agent-plugins"), } }
go
func NewAgent(opts ...Option) Agent { options := newOptions(opts...) if !flag.Parsed() { config.DefineDirFlag() for _, p := range options.Plugins { name := p.String() infraLogger.Debugf("registering flags for: %q", name) config.DefineFlagsFor(name) } flag.Parse() } return &agent{ opts: options, tracer: measure.NewTracer("agent-plugins"), } }
[ "func", "NewAgent", "(", "opts", "...", "Option", ")", "Agent", "{", "options", ":=", "newOptions", "(", "opts", "...", ")", "\n\n", "if", "!", "flag", ".", "Parsed", "(", ")", "{", "config", ".", "DefineDirFlag", "(", ")", "\n", "for", "_", ",", "...
// NewAgent creates a new agent using given options and registers all flags // defined for plugins via config.ForPlugin.
[ "NewAgent", "creates", "a", "new", "agent", "using", "given", "options", "and", "registers", "all", "flags", "defined", "for", "plugins", "via", "config", ".", "ForPlugin", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/agent/agent.go#L76-L93
4,449
ligato/cn-infra
agent/agent.go
Run
func (a *agent) Run() error { if err := a.Start(); err != nil { return err } return a.Wait() }
go
func (a *agent) Run() error { if err := a.Start(); err != nil { return err } return a.Wait() }
[ "func", "(", "a", "*", "agent", ")", "Run", "(", ")", "error", "{", "if", "err", ":=", "a", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "a", ".", "Wait", "(", ")", "\n", "}" ]
// Run runs the agent. Run will not return until a SIGINT, SIGTERM, or SIGKILL is received
[ "Run", "runs", "the", "agent", ".", "Run", "will", "not", "return", "until", "a", "SIGINT", "SIGTERM", "or", "SIGKILL", "is", "received" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/agent/agent.go#L126-L131
4,450
ligato/cn-infra
examples/kafka-plugin/manual-partitioner/main.go
asyncEventHandler
func (plugin *ExamplePlugin) asyncEventHandler() { plugin.Log.Info("Started Kafka async event handler...") asyncSuccessCounter := 0 if messageCountNum == 0 { plugin.asyncSuccess = 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()) // Note: mark the offset if required if message.GetPartition() != asyncMessagePartition { plugin.Log.Errorf("Received async message with unexpected partition: %v", message.GetOffset()) } if message.GetOffset() < messageOffset { plugin.Log.Errorf("Received async message with unexpected offset: %v", message.GetOffset()) } // Success callback channel 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()) // Note: mark the offset if required asyncSuccessCounter++ if asyncSuccessCounter == 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...") asyncSuccessCounter := 0 if messageCountNum == 0 { plugin.asyncSuccess = 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()) // Note: mark the offset if required if message.GetPartition() != asyncMessagePartition { plugin.Log.Errorf("Received async message with unexpected partition: %v", message.GetOffset()) } if message.GetOffset() < messageOffset { plugin.Log.Errorf("Received async message with unexpected offset: %v", message.GetOffset()) } // Success callback channel 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()) // Note: mark the offset if required asyncSuccessCounter++ if asyncSuccessCounter == 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", "asyncSuccessCounter", ":=", "0", "\n", "if", "messageCountNum", "==", "0", "{", "plugin", ".", "asyncSuc...
// asyncEventHandler is a Kafka consumer asynchronously processing events from // a channel associated with a specific topic, partition and a starting offset. // 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", "partition", "and", "a", "starting", "offset", ".", "If", "a", "producer", "sends", "a", "messa...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/kafka-plugin/manual-partitioner/main.go#L306-L340
4,451
ligato/cn-infra
examples/tutorials/06_plugin_lookup/plugin1.go
SetPlace
func (p *HelloWorld) SetPlace(world, place string) { log.Printf("%s was placed %s", world, place) }
go
func (p *HelloWorld) SetPlace(world, place string) { log.Printf("%s was placed %s", world, place) }
[ "func", "(", "p", "*", "HelloWorld", ")", "SetPlace", "(", "world", ",", "place", "string", ")", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "world", ",", "place", ")", "\n", "}" ]
// SetPlace is an exported method that allows other plugins to set some internal parameters
[ "SetPlace", "is", "an", "exported", "method", "that", "allows", "other", "plugins", "to", "set", "some", "internal", "parameters" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/tutorials/06_plugin_lookup/plugin1.go#L36-L38
4,452
ligato/cn-infra
examples/flags-lib/main.go
RegisterFlags
func RegisterFlags() { fmt.Println("Registering flags...") flag.StringVar(&testFlagString, "ep-string", "my-value", "Example of a string flag.") flag.IntVar(&testFlagInt, "ep-int", 1122, "Example of an int flag.") flag.Int64Var(&testFlagInt64, "ep-int64", -3344, "Example of an int64 flag.") flag.UintVar(&testFlagUint, "ep-uint", 5566, "Example of a uint flag.") flag.Uint64Var(&testFlagUint64, "ep-uint64", 7788, "Example of a uint64 flag.") flag.BoolVar(&testFlagBool, "ep-bool", true, "Example of a bool flag.") flag.DurationVar(&testFlagDur, "ep-duration", time.Second*5, "Example of a duration flag.") }
go
func RegisterFlags() { fmt.Println("Registering flags...") flag.StringVar(&testFlagString, "ep-string", "my-value", "Example of a string flag.") flag.IntVar(&testFlagInt, "ep-int", 1122, "Example of an int flag.") flag.Int64Var(&testFlagInt64, "ep-int64", -3344, "Example of an int64 flag.") flag.UintVar(&testFlagUint, "ep-uint", 5566, "Example of a uint flag.") flag.Uint64Var(&testFlagUint64, "ep-uint64", 7788, "Example of a uint64 flag.") flag.BoolVar(&testFlagBool, "ep-bool", true, "Example of a bool flag.") flag.DurationVar(&testFlagDur, "ep-duration", time.Second*5, "Example of a duration flag.") }
[ "func", "RegisterFlags", "(", ")", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "flag", ".", "StringVar", "(", "&", "testFlagString", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flag", ".", "IntVar", "(", "&", "testF...
// RegisterFlags contains examples of how to register flags of various types.
[ "RegisterFlags", "contains", "examples", "of", "how", "to", "register", "flags", "of", "various", "types", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/flags-lib/main.go#L33-L49
4,453
ligato/cn-infra
examples/flags-lib/main.go
PrintFlags
func PrintFlags() { fmt.Println("Printing flags...") fmt.Printf("testFlagString:'%s'\n", testFlagString) fmt.Printf("testFlagInt:'%d'\n", testFlagInt) fmt.Printf("testFlagInt64:'%d'\n", testFlagInt64) fmt.Printf("testFlagUint:'%d'\n", testFlagUint) fmt.Printf("testFlagUint64:'%d'\n", testFlagUint64) fmt.Printf("testFlagBool:'%v'\n", testFlagBool) fmt.Printf("testFlagDur:'%v'\n", testFlagDur) }
go
func PrintFlags() { fmt.Println("Printing flags...") fmt.Printf("testFlagString:'%s'\n", testFlagString) fmt.Printf("testFlagInt:'%d'\n", testFlagInt) fmt.Printf("testFlagInt64:'%d'\n", testFlagInt64) fmt.Printf("testFlagUint:'%d'\n", testFlagUint) fmt.Printf("testFlagUint64:'%d'\n", testFlagUint64) fmt.Printf("testFlagBool:'%v'\n", testFlagBool) fmt.Printf("testFlagDur:'%v'\n", testFlagDur) }
[ "func", "PrintFlags", "(", ")", "{", "fmt", ".", "Println", "(", "\"", "\"", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "testFlagString", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "testFlagInt", ")", "\n", "...
// PrintFlags shows the runtime values of CLI flags.
[ "PrintFlags", "shows", "the", "runtime", "values", "of", "CLI", "flags", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/flags-lib/main.go#L57-L66
4,454
ligato/cn-infra
datasync/syncbase/transport_adapter.go
Watch
func (adapter *Adapter) Watch(resyncName string, changeChan chan datasync.ChangeEvent, resyncChan chan datasync.ResyncEvent, keyPrefixes ...string) (datasync.WatchRegistration, error) { if adapter.Watcher != nil { return adapter.Watcher.Watch(resyncName, changeChan, resyncChan, keyPrefixes...) } logrus.DefaultLogger().Debug("KeyValProtoWatcher is nil") return nil, nil }
go
func (adapter *Adapter) Watch(resyncName string, changeChan chan datasync.ChangeEvent, resyncChan chan datasync.ResyncEvent, keyPrefixes ...string) (datasync.WatchRegistration, error) { if adapter.Watcher != nil { return adapter.Watcher.Watch(resyncName, changeChan, resyncChan, keyPrefixes...) } logrus.DefaultLogger().Debug("KeyValProtoWatcher is nil") return nil, nil }
[ "func", "(", "adapter", "*", "Adapter", ")", "Watch", "(", "resyncName", "string", ",", "changeChan", "chan", "datasync", ".", "ChangeEvent", ",", "resyncChan", "chan", "datasync", ".", "ResyncEvent", ",", "keyPrefixes", "...", "string", ")", "(", "datasync", ...
// Watch uses Kafka KeyValProtoWatcher Topic KeyValProtoWatcher.
[ "Watch", "uses", "Kafka", "KeyValProtoWatcher", "Topic", "KeyValProtoWatcher", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/transport_adapter.go#L30-L39
4,455
ligato/cn-infra
datasync/syncbase/transport_adapter.go
Put
func (adapter *Adapter) Put(key string, data proto.Message) error { if adapter.Publisher != nil { return adapter.Publisher.Put(key, data) } return nil }
go
func (adapter *Adapter) Put(key string, data proto.Message) error { if adapter.Publisher != nil { return adapter.Publisher.Put(key, data) } return nil }
[ "func", "(", "adapter", "*", "Adapter", ")", "Put", "(", "key", "string", ",", "data", "proto", ".", "Message", ")", "error", "{", "if", "adapter", ".", "Publisher", "!=", "nil", "{", "return", "adapter", ".", "Publisher", ".", "Put", "(", "key", ","...
// Put uses Kafka KeyValProtoWatcher Topic KeyProtoValWriter.
[ "Put", "uses", "Kafka", "KeyValProtoWatcher", "Topic", "KeyProtoValWriter", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/transport_adapter.go#L42-L48
4,456
ligato/cn-infra
examples/datasync-plugin/main.go
AfterInit
func (p *ExamplePlugin) AfterInit() error { resync.DefaultPlugin.DoResync() go p.etcdPublisher() go p.closeExample() return nil }
go
func (p *ExamplePlugin) AfterInit() error { resync.DefaultPlugin.DoResync() go p.etcdPublisher() go p.closeExample() return nil }
[ "func", "(", "p", "*", "ExamplePlugin", ")", "AfterInit", "(", ")", "error", "{", "resync", ".", "DefaultPlugin", ".", "DoResync", "(", ")", "\n\n", "go", "p", ".", "etcdPublisher", "(", ")", "\n\n", "go", "p", ".", "closeExample", "(", ")", "\n\n", ...
// AfterInit starts the publisher and prepares for the shutdown.
[ "AfterInit", "starts", "the", "publisher", "and", "prepares", "for", "the", "shutdown", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/datasync-plugin/main.go#L106-L114
4,457
ligato/cn-infra
examples/datasync-plugin/main.go
Close
func (p *ExamplePlugin) Close() error { p.Log.Info("Close plugin..") // Close the watcher p.cancel() p.wg.Wait() return nil }
go
func (p *ExamplePlugin) Close() error { p.Log.Info("Close plugin..") // Close the watcher p.cancel() p.wg.Wait() return nil }
[ "func", "(", "p", "*", "ExamplePlugin", ")", "Close", "(", ")", "error", "{", "p", ".", "Log", ".", "Info", "(", "\"", "\"", ")", "\n", "// Close the watcher", "p", ".", "cancel", "(", ")", "\n", "p", ".", "wg", ".", "Wait", "(", ")", "\n", "re...
// Close shutdowns both the publisher and the consumer. // Channels used to propagate data resync and data change events are closed // as well.
[ "Close", "shutdowns", "both", "the", "publisher", "and", "the", "consumer", ".", "Channels", "used", "to", "propagate", "data", "resync", "and", "data", "change", "events", "are", "closed", "as", "well", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/datasync-plugin/main.go#L119-L125
4,458
ligato/cn-infra
examples/datasync-plugin/main.go
subscribeWatcher
func (p *ExamplePlugin) subscribeWatcher() (err error) { prefix := etcdKeyPrefix(p.ServiceLabel.GetAgentLabel()) p.Log.Infof("Prefix: %v", prefix) p.watchDataReg, err = p.Watcher.Watch("ExamplePlugin", p.changeChannel, p.resyncChannel, prefix) if err != nil { return err } p.Log.Info("KeyValProtoWatcher subscribed") return nil }
go
func (p *ExamplePlugin) subscribeWatcher() (err error) { prefix := etcdKeyPrefix(p.ServiceLabel.GetAgentLabel()) p.Log.Infof("Prefix: %v", prefix) p.watchDataReg, err = p.Watcher.Watch("ExamplePlugin", p.changeChannel, p.resyncChannel, prefix) if err != nil { return err } p.Log.Info("KeyValProtoWatcher subscribed") return nil }
[ "func", "(", "p", "*", "ExamplePlugin", ")", "subscribeWatcher", "(", ")", "(", "err", "error", ")", "{", "prefix", ":=", "etcdKeyPrefix", "(", "p", ".", "ServiceLabel", ".", "GetAgentLabel", "(", ")", ")", "\n", "p", ".", "Log", ".", "Infof", "(", "...
// subscribeWatcher subscribes for data change and data resync events. // Events are delivered to the consumer via the selected channels. // ETCD watcher adapter is used to perform the registration behind the scenes.
[ "subscribeWatcher", "subscribes", "for", "data", "change", "and", "data", "resync", "events", ".", "Events", "are", "delivered", "to", "the", "consumer", "via", "the", "selected", "channels", ".", "ETCD", "watcher", "adapter", "is", "used", "to", "perform", "t...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/datasync-plugin/main.go#L130-L143
4,459
ligato/cn-infra
examples/datasync-plugin/main.go
etcdPublisher
func (p *ExamplePlugin) etcdPublisher() { // Wait for the consumer to initialize time.Sleep(1 * time.Second) p.Log.Print("KeyValPublisher started") // Convert data into the proto format. exampleData := p.buildData("string1", 0, true) // PUT: demonstrate how to use the Data Broker Put() API to store // a simple data structure into ETCD. label := etcdKeyPrefixLabel(p.ServiceLabel.GetAgentLabel(), "index") p.Log.Infof("Write data to %v", label) if err := p.Publisher.Put(label, exampleData); err != nil { p.Log.Fatal(err) } // Prepare different set of data. p.Log.Infof("Update data at %v", label) exampleData = p.buildData("string2", 1, false) // UPDATE: demonstrate how use the Data Broker Put() API to change // an already stored data in ETCD. if err := p.Publisher.Put(label, exampleData); err != nil { p.Log.Fatal(err) } // Prepare another different set of data. p.Log.Infof("Update data at %v", label) exampleData = p.buildData("string3", 2, false) // UPDATE: only to demonstrate Unregister functionality if err := p.Publisher.Put(label, exampleData); err != nil { p.Log.Fatal(err) } // Wait for the consumer (change should not be passed to listener) time.Sleep(2 * time.Second) p.publisherDone = true }
go
func (p *ExamplePlugin) etcdPublisher() { // Wait for the consumer to initialize time.Sleep(1 * time.Second) p.Log.Print("KeyValPublisher started") // Convert data into the proto format. exampleData := p.buildData("string1", 0, true) // PUT: demonstrate how to use the Data Broker Put() API to store // a simple data structure into ETCD. label := etcdKeyPrefixLabel(p.ServiceLabel.GetAgentLabel(), "index") p.Log.Infof("Write data to %v", label) if err := p.Publisher.Put(label, exampleData); err != nil { p.Log.Fatal(err) } // Prepare different set of data. p.Log.Infof("Update data at %v", label) exampleData = p.buildData("string2", 1, false) // UPDATE: demonstrate how use the Data Broker Put() API to change // an already stored data in ETCD. if err := p.Publisher.Put(label, exampleData); err != nil { p.Log.Fatal(err) } // Prepare another different set of data. p.Log.Infof("Update data at %v", label) exampleData = p.buildData("string3", 2, false) // UPDATE: only to demonstrate Unregister functionality if err := p.Publisher.Put(label, exampleData); err != nil { p.Log.Fatal(err) } // Wait for the consumer (change should not be passed to listener) time.Sleep(2 * time.Second) p.publisherDone = true }
[ "func", "(", "p", "*", "ExamplePlugin", ")", "etcdPublisher", "(", ")", "{", "// Wait for the consumer to initialize", "time", ".", "Sleep", "(", "1", "*", "time", ".", "Second", ")", "\n\n", "p", ".", "Log", ".", "Print", "(", "\"", "\"", ")", "\n\n", ...
// etcdPublisher creates a simple data, then demonstrates CREATE and UPDATE // operations with ETCD.
[ "etcdPublisher", "creates", "a", "simple", "data", "then", "demonstrates", "CREATE", "and", "UPDATE", "operations", "with", "ETCD", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/datasync-plugin/main.go#L147-L186
4,460
ligato/cn-infra
examples/datasync-plugin/main.go
buildData
func (p *ExamplePlugin) buildData(stringVal string, uint32Val uint32, boolVal bool) *etcdexample.EtcdExample { return &etcdexample.EtcdExample{ StringVal: stringVal, Uint32Val: uint32Val, BoolVal: boolVal, } }
go
func (p *ExamplePlugin) buildData(stringVal string, uint32Val uint32, boolVal bool) *etcdexample.EtcdExample { return &etcdexample.EtcdExample{ StringVal: stringVal, Uint32Val: uint32Val, BoolVal: boolVal, } }
[ "func", "(", "p", "*", "ExamplePlugin", ")", "buildData", "(", "stringVal", "string", ",", "uint32Val", "uint32", ",", "boolVal", "bool", ")", "*", "etcdexample", ".", "EtcdExample", "{", "return", "&", "etcdexample", ".", "EtcdExample", "{", "StringVal", ":...
// Create simple ETCD data structure with provided data values.
[ "Create", "simple", "ETCD", "data", "structure", "with", "provided", "data", "values", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/datasync-plugin/main.go#L269-L275
4,461
ligato/cn-infra
logging/logmanager/plugin_impl_log_manager.go
Init
func (p *Plugin) Init() error { if p.Cfg != nil { if p.Config == nil { p.Config = NewConf() } _, err := p.Cfg.LoadValue(p.Config) if err != nil { return err } p.Log.Debugf("logs config: %+v", p.Config) // Handle default log level. Prefer value from environmental variable defaultLogLvl := os.Getenv("INITIAL_LOGLVL") if defaultLogLvl == "" { defaultLogLvl = p.Config.DefaultLevel } if defaultLogLvl != "" { if err := p.LogRegistry.SetLevel("default", defaultLogLvl); err != nil { p.Log.Warnf("setting default log level failed: %v", err) } else { // All loggers created up to this point were created with initial log level set (defined // via INITIAL_LOGLVL env. variable with value 'info' by default), so at first, let's set default // log level for all of them. for loggerName := range p.LogRegistry.ListLoggers() { logger, exists := p.LogRegistry.Lookup(loggerName) if !exists { continue } logger.SetLevel(logging.ParseLogLevel(defaultLogLvl)) } } } // Handle config file log levels for _, logCfgEntry := range p.Config.Loggers { // Put log/level entries from configuration file to the registry. if err := p.LogRegistry.SetLevel(logCfgEntry.Name, logCfgEntry.Level); err != nil { // Intentionally just log warn & not propagate the error (it is minor thing to interrupt startup) p.Log.Warnf("setting log level %s for logger %s failed: %v", logCfgEntry.Level, logCfgEntry.Name, err) } } if len(p.Config.Hooks) > 0 { p.Log.Info("configuring log hooks") for hookName, hookConfig := range p.Config.Hooks { if err := p.addHook(hookName, hookConfig); err != nil { p.Log.Warnf("configuring log hook %s failed: %v", hookName, err) } } } } return nil }
go
func (p *Plugin) Init() error { if p.Cfg != nil { if p.Config == nil { p.Config = NewConf() } _, err := p.Cfg.LoadValue(p.Config) if err != nil { return err } p.Log.Debugf("logs config: %+v", p.Config) // Handle default log level. Prefer value from environmental variable defaultLogLvl := os.Getenv("INITIAL_LOGLVL") if defaultLogLvl == "" { defaultLogLvl = p.Config.DefaultLevel } if defaultLogLvl != "" { if err := p.LogRegistry.SetLevel("default", defaultLogLvl); err != nil { p.Log.Warnf("setting default log level failed: %v", err) } else { // All loggers created up to this point were created with initial log level set (defined // via INITIAL_LOGLVL env. variable with value 'info' by default), so at first, let's set default // log level for all of them. for loggerName := range p.LogRegistry.ListLoggers() { logger, exists := p.LogRegistry.Lookup(loggerName) if !exists { continue } logger.SetLevel(logging.ParseLogLevel(defaultLogLvl)) } } } // Handle config file log levels for _, logCfgEntry := range p.Config.Loggers { // Put log/level entries from configuration file to the registry. if err := p.LogRegistry.SetLevel(logCfgEntry.Name, logCfgEntry.Level); err != nil { // Intentionally just log warn & not propagate the error (it is minor thing to interrupt startup) p.Log.Warnf("setting log level %s for logger %s failed: %v", logCfgEntry.Level, logCfgEntry.Name, err) } } if len(p.Config.Hooks) > 0 { p.Log.Info("configuring log hooks") for hookName, hookConfig := range p.Config.Hooks { if err := p.addHook(hookName, hookConfig); err != nil { p.Log.Warnf("configuring log hook %s failed: %v", hookName, err) } } } } return nil }
[ "func", "(", "p", "*", "Plugin", ")", "Init", "(", ")", "error", "{", "if", "p", ".", "Cfg", "!=", "nil", "{", "if", "p", ".", "Config", "==", "nil", "{", "p", ".", "Config", "=", "NewConf", "(", ")", "\n", "}", "\n\n", "_", ",", "err", ":=...
// Init does nothing
[ "Init", "does", "nothing" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logmanager/plugin_impl_log_manager.go#L59-L113
4,462
ligato/cn-infra
logging/logmanager/plugin_impl_log_manager.go
listLoggers
func (p *Plugin) listLoggers() (loggers []LoggerData) { for logger, lvl := range p.LogRegistry.ListLoggers() { loggers = append(loggers, LoggerData{ Logger: logger, Level: lvl, }) } return loggers }
go
func (p *Plugin) listLoggers() (loggers []LoggerData) { for logger, lvl := range p.LogRegistry.ListLoggers() { loggers = append(loggers, LoggerData{ Logger: logger, Level: lvl, }) } return loggers }
[ "func", "(", "p", "*", "Plugin", ")", "listLoggers", "(", ")", "(", "loggers", "[", "]", "LoggerData", ")", "{", "for", "logger", ",", "lvl", ":=", "range", "p", ".", "LogRegistry", ".", "ListLoggers", "(", ")", "{", "loggers", "=", "append", "(", ...
// ListLoggers lists all registered loggers.
[ "ListLoggers", "lists", "all", "registered", "loggers", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logmanager/plugin_impl_log_manager.go#L135-L143
4,463
ligato/cn-infra
logging/logmanager/plugin_impl_log_manager.go
setLoggerLogLevel
func (p *Plugin) setLoggerLogLevel(name string, level string) error { p.Log.Debugf("SetLogLevel name %q, level %q", name, level) return p.LogRegistry.SetLevel(name, level) }
go
func (p *Plugin) setLoggerLogLevel(name string, level string) error { p.Log.Debugf("SetLogLevel name %q, level %q", name, level) return p.LogRegistry.SetLevel(name, level) }
[ "func", "(", "p", "*", "Plugin", ")", "setLoggerLogLevel", "(", "name", "string", ",", "level", "string", ")", "error", "{", "p", ".", "Log", ".", "Debugf", "(", "\"", "\"", ",", "name", ",", "level", ")", "\n\n", "return", "p", ".", "LogRegistry", ...
// setLoggerLogLevel modifies the log level of the all loggers in a plugin
[ "setLoggerLogLevel", "modifies", "the", "log", "level", "of", "the", "all", "loggers", "in", "a", "plugin" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logmanager/plugin_impl_log_manager.go#L146-L150
4,464
ligato/cn-infra
logging/logmanager/plugin_impl_log_manager.go
logLevelHandler
func (p *Plugin) logLevelHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { p.Log.Infof("Path: %s", req.URL.Path) vars := mux.Vars(req) if vars == nil { formatter.JSON(w, http.StatusNotFound, struct{}{}) return } err := p.setLoggerLogLevel(vars[loggerVarName], vars[levelVarName]) if err != nil { formatter.JSON(w, http.StatusNotFound, struct{ Error string }{err.Error()}) return } formatter.JSON(w, http.StatusOK, LoggerData{ Logger: vars[loggerVarName], Level: vars[levelVarName], }) } }
go
func (p *Plugin) logLevelHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { p.Log.Infof("Path: %s", req.URL.Path) vars := mux.Vars(req) if vars == nil { formatter.JSON(w, http.StatusNotFound, struct{}{}) return } err := p.setLoggerLogLevel(vars[loggerVarName], vars[levelVarName]) if err != nil { formatter.JSON(w, http.StatusNotFound, struct{ Error string }{err.Error()}) return } formatter.JSON(w, http.StatusOK, LoggerData{ Logger: vars[loggerVarName], Level: vars[levelVarName], }) } }
[ "func", "(", "p", "*", "Plugin", ")", "logLevelHandler", "(", "formatter", "*", "render", ".", "Render", ")", "http", ".", "HandlerFunc", "{", "return", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{",...
// logLevelHandler processes requests to set log level on loggers in a plugin
[ "logLevelHandler", "processes", "requests", "to", "set", "log", "level", "on", "loggers", "in", "a", "plugin" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logmanager/plugin_impl_log_manager.go#L153-L174
4,465
ligato/cn-infra
logging/logmanager/plugin_impl_log_manager.go
listLoggersHandler
func (p *Plugin) listLoggersHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { formatter.JSON(w, http.StatusOK, p.listLoggers()) } }
go
func (p *Plugin) listLoggersHandler(formatter *render.Render) http.HandlerFunc { return func(w http.ResponseWriter, req *http.Request) { formatter.JSON(w, http.StatusOK, p.listLoggers()) } }
[ "func", "(", "p", "*", "Plugin", ")", "listLoggersHandler", "(", "formatter", "*", "render", ".", "Render", ")", "http", ".", "HandlerFunc", "{", "return", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "...
// listLoggersHandler processes requests to list all registered loggers
[ "listLoggersHandler", "processes", "requests", "to", "list", "all", "registered", "loggers" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logmanager/plugin_impl_log_manager.go#L177-L181
4,466
ligato/cn-infra
idxmap/mem/inmemory_name_mapping.go
Clear
func (mem *memNamedMapping) Clear() { names := mem.ListAllNames() for _, item := range names { mem.removeNameIdxSync(item) } }
go
func (mem *memNamedMapping) Clear() { names := mem.ListAllNames() for _, item := range names { mem.removeNameIdxSync(item) } }
[ "func", "(", "mem", "*", "memNamedMapping", ")", "Clear", "(", ")", "{", "names", ":=", "mem", ".", "ListAllNames", "(", ")", "\n", "for", "_", ",", "item", ":=", "range", "names", "{", "mem", ".", "removeNameIdxSync", "(", "item", ")", "\n", "}", ...
// Clear removes all entries from name-to-index mapping
[ "Clear", "removes", "all", "entries", "from", "name", "-", "to", "-", "index", "mapping" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/idxmap/mem/inmemory_name_mapping.go#L98-L103
4,467
ligato/cn-infra
idxmap/mem/inmemory_name_mapping.go
ListAllNames
func (mem *memNamedMapping) ListAllNames() (names []string) { mem.access.RLock() defer mem.access.RUnlock() var ret []string for name := range mem.nameToIdx { ret = append(ret, name) } return ret }
go
func (mem *memNamedMapping) ListAllNames() (names []string) { mem.access.RLock() defer mem.access.RUnlock() var ret []string for name := range mem.nameToIdx { ret = append(ret, name) } return ret }
[ "func", "(", "mem", "*", "memNamedMapping", ")", "ListAllNames", "(", ")", "(", "names", "[", "]", "string", ")", "{", "mem", ".", "access", ".", "RLock", "(", ")", "\n", "defer", "mem", ".", "access", ".", "RUnlock", "(", ")", "\n\n", "var", "ret"...
// ListAllNames returns all names in the mapping.
[ "ListAllNames", "returns", "all", "names", "in", "the", "mapping", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/idxmap/mem/inmemory_name_mapping.go#L123-L134
4,468
ligato/cn-infra
idxmap/mem/inmemory_name_mapping.go
ListNames
func (mem *memNamedMapping) ListNames(field string, value string) []string { mem.access.RLock() defer mem.access.RUnlock() ix, found := mem.indexes[field] if !found { return nil } set, found := ix[value] if !found { return nil } return set.content() }
go
func (mem *memNamedMapping) ListNames(field string, value string) []string { mem.access.RLock() defer mem.access.RUnlock() ix, found := mem.indexes[field] if !found { return nil } set, found := ix[value] if !found { return nil } return set.content() }
[ "func", "(", "mem", "*", "memNamedMapping", ")", "ListNames", "(", "field", "string", ",", "value", "string", ")", "[", "]", "string", "{", "mem", ".", "access", ".", "RLock", "(", ")", "\n", "defer", "mem", ".", "access", ".", "RUnlock", "(", ")", ...
// ListNames looks up the items by secondary indexes. It returns all // names matching the selection.
[ "ListNames", "looks", "up", "the", "items", "by", "secondary", "indexes", ".", "It", "returns", "all", "names", "matching", "the", "selection", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/idxmap/mem/inmemory_name_mapping.go#L159-L174
4,469
ligato/cn-infra
utils/structs/structs_reflection.go
ListExportedFields
func ListExportedFields(val interface{}, predicates ...ExportedPredicate) []*reflect.StructField { valType := reflect.Indirect(reflect.ValueOf(val)).Type() len := valType.NumField() ret := []*reflect.StructField{} for i := 0; i < len; i++ { structField := valType.Field(i) if FieldExported(&structField, predicates...) { ret = append(ret, &structField) } } return ret }
go
func ListExportedFields(val interface{}, predicates ...ExportedPredicate) []*reflect.StructField { valType := reflect.Indirect(reflect.ValueOf(val)).Type() len := valType.NumField() ret := []*reflect.StructField{} for i := 0; i < len; i++ { structField := valType.Field(i) if FieldExported(&structField, predicates...) { ret = append(ret, &structField) } } return ret }
[ "func", "ListExportedFields", "(", "val", "interface", "{", "}", ",", "predicates", "...", "ExportedPredicate", ")", "[", "]", "*", "reflect", ".", "StructField", "{", "valType", ":=", "reflect", ".", "Indirect", "(", "reflect", ".", "ValueOf", "(", "val", ...
// ListExportedFields returns all fields of a structure that starts wit uppercase letter
[ "ListExportedFields", "returns", "all", "fields", "of", "a", "structure", "that", "starts", "wit", "uppercase", "letter" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/utils/structs/structs_reflection.go#L55-L68
4,470
ligato/cn-infra
utils/structs/structs_reflection.go
FieldExported
func FieldExported(field *reflect.StructField, predicates ...ExportedPredicate) (exported bool) { if field.Name[0] == strings.ToUpper(string(field.Name[0]))[0] { expPredic := true for _, predicate := range predicates { if !predicate(field) { expPredic = false break } } return expPredic } return false }
go
func FieldExported(field *reflect.StructField, predicates ...ExportedPredicate) (exported bool) { if field.Name[0] == strings.ToUpper(string(field.Name[0]))[0] { expPredic := true for _, predicate := range predicates { if !predicate(field) { expPredic = false break } } return expPredic } return false }
[ "func", "FieldExported", "(", "field", "*", "reflect", ".", "StructField", ",", "predicates", "...", "ExportedPredicate", ")", "(", "exported", "bool", ")", "{", "if", "field", ".", "Name", "[", "0", "]", "==", "strings", ".", "ToUpper", "(", "string", "...
// FieldExported returns true if field name starts with uppercase
[ "FieldExported", "returns", "true", "if", "field", "name", "starts", "with", "uppercase" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/utils/structs/structs_reflection.go#L74-L88
4,471
ligato/cn-infra
utils/structs/structs_reflection.go
ListExportedFieldsPtrs
func ListExportedFieldsPtrs(val interface{}, predicates ...ExportedPredicate) ( fields []*reflect.StructField, valPtrs []interface{}) { rVal := reflect.Indirect(reflect.ValueOf(val)) valPtrs = []interface{}{} fields = []*reflect.StructField{} for i := 0; i < rVal.NumField(); i++ { field := rVal.Field(i) structField := rVal.Type().Field(i) if !FieldExported(&structField, predicates...) { continue } switch field.Kind() { case reflect.Ptr, reflect.Interface: if field.IsNil() { p := reflect.New(field.Type().Elem()) field.Set(p) valPtrs = append(valPtrs, p.Interface()) } else { valPtrs = append(valPtrs, field.Interface()) } case reflect.Slice, reflect.Chan, reflect.Map: if field.IsNil() { p := reflect.New(field.Type()) field.Set(p.Elem()) valPtrs = append(valPtrs, field.Addr().Interface()) } else { valPtrs = append(valPtrs, field.Interface()) } default: if field.CanAddr() { valPtrs = append(valPtrs, field.Addr().Interface()) } else if field.IsValid() { valPtrs = append(valPtrs, field.Interface()) } else { panic("invalid field") } } fields = append(fields, &structField) } return fields, valPtrs }
go
func ListExportedFieldsPtrs(val interface{}, predicates ...ExportedPredicate) ( fields []*reflect.StructField, valPtrs []interface{}) { rVal := reflect.Indirect(reflect.ValueOf(val)) valPtrs = []interface{}{} fields = []*reflect.StructField{} for i := 0; i < rVal.NumField(); i++ { field := rVal.Field(i) structField := rVal.Type().Field(i) if !FieldExported(&structField, predicates...) { continue } switch field.Kind() { case reflect.Ptr, reflect.Interface: if field.IsNil() { p := reflect.New(field.Type().Elem()) field.Set(p) valPtrs = append(valPtrs, p.Interface()) } else { valPtrs = append(valPtrs, field.Interface()) } case reflect.Slice, reflect.Chan, reflect.Map: if field.IsNil() { p := reflect.New(field.Type()) field.Set(p.Elem()) valPtrs = append(valPtrs, field.Addr().Interface()) } else { valPtrs = append(valPtrs, field.Interface()) } default: if field.CanAddr() { valPtrs = append(valPtrs, field.Addr().Interface()) } else if field.IsValid() { valPtrs = append(valPtrs, field.Interface()) } else { panic("invalid field") } } fields = append(fields, &structField) } return fields, valPtrs }
[ "func", "ListExportedFieldsPtrs", "(", "val", "interface", "{", "}", ",", "predicates", "...", "ExportedPredicate", ")", "(", "fields", "[", "]", "*", "reflect", ".", "StructField", ",", "valPtrs", "[", "]", "interface", "{", "}", ")", "{", "rVal", ":=", ...
// ListExportedFieldsPtrs iterates struct fields and return slice of pointers to field values
[ "ListExportedFieldsPtrs", "iterates", "struct", "fields", "and", "return", "slice", "of", "pointers", "to", "field", "values" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/utils/structs/structs_reflection.go#L91-L136
4,472
ligato/cn-infra
logging/logrus/logger.go
InitTag
func (logger *Logger) InitTag(tag ...string) { var t string var index uint64 // first index if len(tag) > 0 { t = tag[0] } else { id, err := uuid.NewV4() if err != nil { panic(fmt.Errorf("error generating uuid: " + err.Error())) } t = id.String()[0:8] } logger.tagMap.Store(index, t) }
go
func (logger *Logger) InitTag(tag ...string) { var t string var index uint64 // first index if len(tag) > 0 { t = tag[0] } else { id, err := uuid.NewV4() if err != nil { panic(fmt.Errorf("error generating uuid: " + err.Error())) } t = id.String()[0:8] } logger.tagMap.Store(index, t) }
[ "func", "(", "logger", "*", "Logger", ")", "InitTag", "(", "tag", "...", "string", ")", "{", "var", "t", "string", "\n", "var", "index", "uint64", "// first index", "\n", "if", "len", "(", "tag", ")", ">", "0", "{", "t", "=", "tag", "[", "0", "]"...
// InitTag sets the tag for the main thread.
[ "InitTag", "sets", "the", "tag", "for", "the", "main", "thread", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L117-L130
4,473
ligato/cn-infra
logging/logrus/logger.go
GetTag
func (logger *Logger) GetTag() string { goID := logger.curGoroutineID() if tagVal, found := logger.tagMap.Load(goID); !found { return "" } else if tag, ok := tagVal.(string); ok { return tag } panic(fmt.Errorf("cannot cast log tag from map to string")) }
go
func (logger *Logger) GetTag() string { goID := logger.curGoroutineID() if tagVal, found := logger.tagMap.Load(goID); !found { return "" } else if tag, ok := tagVal.(string); ok { return tag } panic(fmt.Errorf("cannot cast log tag from map to string")) }
[ "func", "(", "logger", "*", "Logger", ")", "GetTag", "(", ")", "string", "{", "goID", ":=", "logger", ".", "curGoroutineID", "(", ")", "\n", "if", "tagVal", ",", "found", ":=", "logger", ".", "tagMap", ".", "Load", "(", "goID", ")", ";", "!", "foun...
// GetTag returns the tag identifying the caller's go routine.
[ "GetTag", "returns", "the", "tag", "identifying", "the", "caller", "s", "go", "routine", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L133-L141
4,474
ligato/cn-infra
logging/logrus/logger.go
SetTag
func (logger *Logger) SetTag(tag ...string) { goID := logger.curGoroutineID() var t string if len(tag) > 0 { t = tag[0] } else { id, err := uuid.NewV4() if err != nil { panic(fmt.Errorf("error generating uuid: " + err.Error())) } t = id.String()[0:8] } logger.tagMap.Store(goID, t) }
go
func (logger *Logger) SetTag(tag ...string) { goID := logger.curGoroutineID() var t string if len(tag) > 0 { t = tag[0] } else { id, err := uuid.NewV4() if err != nil { panic(fmt.Errorf("error generating uuid: " + err.Error())) } t = id.String()[0:8] } logger.tagMap.Store(goID, t) }
[ "func", "(", "logger", "*", "Logger", ")", "SetTag", "(", "tag", "...", "string", ")", "{", "goID", ":=", "logger", ".", "curGoroutineID", "(", ")", "\n", "var", "t", "string", "\n", "if", "len", "(", "tag", ")", ">", "0", "{", "t", "=", "tag", ...
// SetTag allows to define a string tag for the current go routine. Otherwise // numeric identification is used.
[ "SetTag", "allows", "to", "define", "a", "string", "tag", "for", "the", "current", "go", "routine", ".", "Otherwise", "numeric", "identification", "is", "used", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L145-L158
4,475
ligato/cn-infra
logging/logrus/logger.go
ClearTag
func (logger *Logger) ClearTag() { goID := logger.curGoroutineID() logger.tagMap.Delete(goID) }
go
func (logger *Logger) ClearTag() { goID := logger.curGoroutineID() logger.tagMap.Delete(goID) }
[ "func", "(", "logger", "*", "Logger", ")", "ClearTag", "(", ")", "{", "goID", ":=", "logger", ".", "curGoroutineID", "(", ")", "\n", "logger", ".", "tagMap", ".", "Delete", "(", "goID", ")", "\n", "}" ]
// ClearTag removes the previously set string tag for the current go routine.
[ "ClearTag", "removes", "the", "previously", "set", "string", "tag", "for", "the", "current", "go", "routine", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L161-L164
4,476
ligato/cn-infra
logging/logrus/logger.go
SetStaticFields
func (logger *Logger) SetStaticFields(fields map[string]interface{}) { for key, val := range fields { logger.staticFields.Store(key, val) } }
go
func (logger *Logger) SetStaticFields(fields map[string]interface{}) { for key, val := range fields { logger.staticFields.Store(key, val) } }
[ "func", "(", "logger", "*", "Logger", ")", "SetStaticFields", "(", "fields", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "for", "key", ",", "val", ":=", "range", "fields", "{", "logger", ".", "staticFields", ".", "Store", "(", "key", ...
// SetStaticFields sets a map of fields that will be part of the each subsequent // log entry of the logger
[ "SetStaticFields", "sets", "a", "map", "of", "fields", "that", "will", "be", "part", "of", "the", "each", "subsequent", "log", "entry", "of", "the", "logger" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L168-L172
4,477
ligato/cn-infra
logging/logrus/logger.go
GetStaticFields
func (logger *Logger) GetStaticFields() map[string]interface{} { var wasErr error staticFieldsMap := make(map[string]interface{}) logger.staticFields.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 } staticFieldsMap[key] = v return true }) // throw panic outside of logger.Range() if wasErr != nil { panic(wasErr) } return staticFieldsMap }
go
func (logger *Logger) GetStaticFields() map[string]interface{} { var wasErr error staticFieldsMap := make(map[string]interface{}) logger.staticFields.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 } staticFieldsMap[key] = v return true }) // throw panic outside of logger.Range() if wasErr != nil { panic(wasErr) } return staticFieldsMap }
[ "func", "(", "logger", "*", "Logger", ")", "GetStaticFields", "(", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "var", "wasErr", "error", "\n", "staticFieldsMap", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ...
// GetStaticFields returns currently set map of static fields - key-value pairs // that are automatically added into log entry
[ "GetStaticFields", "returns", "currently", "set", "map", "of", "static", "fields", "-", "key", "-", "value", "pairs", "that", "are", "automatically", "added", "into", "log", "entry" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L176-L197
4,478
ligato/cn-infra
logging/logrus/logger.go
SetOutput
func (logger *Logger) SetOutput(out io.Writer) { unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std)) old := logger.std logger.std.Out = out atomic.CompareAndSwapPointer(unsafeStd, unsafe.Pointer(old), unsafe.Pointer(logger.std)) }
go
func (logger *Logger) SetOutput(out io.Writer) { unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std)) old := logger.std logger.std.Out = out atomic.CompareAndSwapPointer(unsafeStd, unsafe.Pointer(old), unsafe.Pointer(logger.std)) }
[ "func", "(", "logger", "*", "Logger", ")", "SetOutput", "(", "out", "io", ".", "Writer", ")", "{", "unsafeStd", ":=", "(", "*", "unsafe", ".", "Pointer", ")", "(", "unsafe", ".", "Pointer", "(", "&", "logger", ".", "std", ")", ")", "\n", "old", "...
// SetOutput sets the standard logger output.
[ "SetOutput", "sets", "the", "standard", "logger", "output", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L205-L211
4,479
ligato/cn-infra
logging/logrus/logger.go
SetFormatter
func (logger *Logger) SetFormatter(formatter lg.Formatter) { unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std)) old := logger.std logger.std.Formatter = formatter atomic.CompareAndSwapPointer(unsafeStd, unsafe.Pointer(old), unsafe.Pointer(logger.std)) }
go
func (logger *Logger) SetFormatter(formatter lg.Formatter) { unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std)) old := logger.std logger.std.Formatter = formatter atomic.CompareAndSwapPointer(unsafeStd, unsafe.Pointer(old), unsafe.Pointer(logger.std)) }
[ "func", "(", "logger", "*", "Logger", ")", "SetFormatter", "(", "formatter", "lg", ".", "Formatter", ")", "{", "unsafeStd", ":=", "(", "*", "unsafe", ".", "Pointer", ")", "(", "unsafe", ".", "Pointer", "(", "&", "logger", ".", "std", ")", ")", "\n", ...
// SetFormatter sets the standard logger formatter.
[ "SetFormatter", "sets", "the", "standard", "logger", "formatter", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L214-L219
4,480
ligato/cn-infra
logging/logrus/logger.go
SetLevel
func (logger *Logger) SetLevel(level logging.LogLevel) { switch level { case logging.PanicLevel: logger.std.Level = lg.PanicLevel case logging.FatalLevel: logger.std.Level = lg.FatalLevel case logging.ErrorLevel: logger.std.Level = lg.ErrorLevel case logging.WarnLevel: logger.std.Level = lg.WarnLevel case logging.InfoLevel: logger.std.Level = lg.InfoLevel case logging.DebugLevel: logger.std.Level = lg.DebugLevel } }
go
func (logger *Logger) SetLevel(level logging.LogLevel) { switch level { case logging.PanicLevel: logger.std.Level = lg.PanicLevel case logging.FatalLevel: logger.std.Level = lg.FatalLevel case logging.ErrorLevel: logger.std.Level = lg.ErrorLevel case logging.WarnLevel: logger.std.Level = lg.WarnLevel case logging.InfoLevel: logger.std.Level = lg.InfoLevel case logging.DebugLevel: logger.std.Level = lg.DebugLevel } }
[ "func", "(", "logger", "*", "Logger", ")", "SetLevel", "(", "level", "logging", ".", "LogLevel", ")", "{", "switch", "level", "{", "case", "logging", ".", "PanicLevel", ":", "logger", ".", "std", ".", "Level", "=", "lg", ".", "PanicLevel", "\n", "case"...
// SetLevel sets the standard logger level.
[ "SetLevel", "sets", "the", "standard", "logger", "level", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L222-L237
4,481
ligato/cn-infra
logging/logrus/logger.go
GetLevel
func (logger *Logger) GetLevel() logging.LogLevel { unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std)) stdVal := (*lg.Logger)(atomic.LoadPointer(unsafeStd)) l := stdVal.Level switch l { case lg.PanicLevel: return logging.PanicLevel case lg.FatalLevel: return logging.FatalLevel case lg.ErrorLevel: return logging.ErrorLevel case lg.WarnLevel: return logging.WarnLevel case lg.InfoLevel: return logging.InfoLevel case lg.DebugLevel: return logging.DebugLevel default: return logging.DebugLevel } }
go
func (logger *Logger) GetLevel() logging.LogLevel { unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std)) stdVal := (*lg.Logger)(atomic.LoadPointer(unsafeStd)) l := stdVal.Level switch l { case lg.PanicLevel: return logging.PanicLevel case lg.FatalLevel: return logging.FatalLevel case lg.ErrorLevel: return logging.ErrorLevel case lg.WarnLevel: return logging.WarnLevel case lg.InfoLevel: return logging.InfoLevel case lg.DebugLevel: return logging.DebugLevel default: return logging.DebugLevel } }
[ "func", "(", "logger", "*", "Logger", ")", "GetLevel", "(", ")", "logging", ".", "LogLevel", "{", "unsafeStd", ":=", "(", "*", "unsafe", ".", "Pointer", ")", "(", "unsafe", ".", "Pointer", "(", "&", "logger", ".", "std", ")", ")", "\n", "stdVal", "...
// GetLevel returns the standard logger level.
[ "GetLevel", "returns", "the", "standard", "logger", "level", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L240-L260
4,482
ligato/cn-infra
logging/logrus/logger.go
AddHook
func (logger *Logger) AddHook(hook lg.Hook) { mux := &sync.Mutex{} unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std)) stdVal := (*lg.Logger)(atomic.LoadPointer(unsafeStd)) old := logger.std mux.Lock() stdVal.Hooks.Add(hook) mux.Unlock() atomic.CompareAndSwapPointer(unsafeStd, unsafe.Pointer(old), unsafe.Pointer(logger.std)) }
go
func (logger *Logger) AddHook(hook lg.Hook) { mux := &sync.Mutex{} unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std)) stdVal := (*lg.Logger)(atomic.LoadPointer(unsafeStd)) old := logger.std mux.Lock() stdVal.Hooks.Add(hook) mux.Unlock() atomic.CompareAndSwapPointer(unsafeStd, unsafe.Pointer(old), unsafe.Pointer(logger.std)) }
[ "func", "(", "logger", "*", "Logger", ")", "AddHook", "(", "hook", "lg", ".", "Hook", ")", "{", "mux", ":=", "&", "sync", ".", "Mutex", "{", "}", "\n\n", "unsafeStd", ":=", "(", "*", "unsafe", ".", "Pointer", ")", "(", "unsafe", ".", "Pointer", "...
// AddHook adds a hook to the standard logger hooks.
[ "AddHook", "adds", "a", "hook", "to", "the", "standard", "logger", "hooks", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L263-L273
4,483
ligato/cn-infra
logging/logrus/logger.go
WithField
func (logger *Logger) WithField(key string, value interface{}) logging.LogWithLevel { return logger.withFields(logging.Fields{key: value}, 1) }
go
func (logger *Logger) WithField(key string, value interface{}) logging.LogWithLevel { return logger.withFields(logging.Fields{key: value}, 1) }
[ "func", "(", "logger", "*", "Logger", ")", "WithField", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "logging", ".", "LogWithLevel", "{", "return", "logger", ".", "withFields", "(", "logging", ".", "Fields", "{", "key", ":", "value", ...
// WithField creates an entry from the standard logger and adds a field to // it. If you want multiple fields, use `WithFields`. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the LogMsg it returns.
[ "WithField", "creates", "an", "entry", "from", "the", "standard", "logger", "and", "adds", "a", "field", "to", "it", ".", "If", "you", "want", "multiple", "fields", "use", "WithFields", ".", "Note", "that", "it", "doesn", "t", "log", "until", "you", "cal...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L280-L282
4,484
ligato/cn-infra
logging/logrus/logger.go
WithFields
func (logger *Logger) WithFields(fields logging.Fields) logging.LogWithLevel { return logger.withFields(fields, 1) }
go
func (logger *Logger) WithFields(fields logging.Fields) logging.LogWithLevel { return logger.withFields(fields, 1) }
[ "func", "(", "logger", "*", "Logger", ")", "WithFields", "(", "fields", "logging", ".", "Fields", ")", "logging", ".", "LogWithLevel", "{", "return", "logger", ".", "withFields", "(", "fields", ",", "1", ")", "\n", "}" ]
// WithFields creates an entry from the standard logger and adds multiple // fields to it. This is simply a helper for `WithField`, invoking it // once for each field. // // Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal // or Panic on the LogMsg it returns.
[ "WithFields", "creates", "an", "entry", "from", "the", "standard", "logger", "and", "adds", "multiple", "fields", "to", "it", ".", "This", "is", "simply", "a", "helper", "for", "WithField", "invoking", "it", "once", "for", "each", "field", ".", "Note", "th...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L290-L292
4,485
ligato/cn-infra
logging/logrus/logger.go
Infoln
func (logger *Logger) Infoln(args ...interface{}) { if logger.std.Level >= lg.InfoLevel { logger.header(1).Infoln(args...) } }
go
func (logger *Logger) Infoln(args ...interface{}) { if logger.std.Level >= lg.InfoLevel { logger.header(1).Infoln(args...) } }
[ "func", "(", "logger", "*", "Logger", ")", "Infoln", "(", "args", "...", "interface", "{", "}", ")", "{", "if", "logger", ".", "std", ".", "Level", ">=", "lg", ".", "InfoLevel", "{", "logger", ".", "header", "(", "1", ")", ".", "Infoln", "(", "ar...
// Infoln logs a message at level Info on the standard logger.
[ "Infoln", "logs", "a", "message", "at", "level", "Info", "on", "the", "standard", "logger", "." ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/logging/logrus/logger.go#L452-L456
4,486
ligato/cn-infra
processmanager/template/template.go
NewTemplateReader
func NewTemplateReader(path string, log logging.Logger) (*Reader, error) { reader := &Reader{ log: log, path: path, } if _, err := os.Stat(path); os.IsNotExist(err) { if err := os.MkdirAll(path, DefaultMode); err != nil { return nil, errors.Errorf("cannot initialize template reader: path processing error: %v", err) } } return reader, nil }
go
func NewTemplateReader(path string, log logging.Logger) (*Reader, error) { reader := &Reader{ log: log, path: path, } if _, err := os.Stat(path); os.IsNotExist(err) { if err := os.MkdirAll(path, DefaultMode); err != nil { return nil, errors.Errorf("cannot initialize template reader: path processing error: %v", err) } } return reader, nil }
[ "func", "NewTemplateReader", "(", "path", "string", ",", "log", "logging", ".", "Logger", ")", "(", "*", "Reader", ",", "error", ")", "{", "reader", ":=", "&", "Reader", "{", "log", ":", "log", ",", "path", ":", "path", ",", "}", "\n\n", "if", "_",...
// NewTemplateReader returns a new instance of template reader with given path. The path is also verified and // crated if not existed
[ "NewTemplateReader", "returns", "a", "new", "instance", "of", "template", "reader", "with", "given", "path", ".", "The", "path", "is", "also", "verified", "and", "crated", "if", "not", "existed" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/template/template.go#L45-L57
4,487
ligato/cn-infra
processmanager/template/template.go
GetAllTemplates
func (r *Reader) GetAllTemplates() ([]*process.Template, error) { var templates []*process.Template entries, err := ioutil.ReadDir(r.path) if err != nil { return templates, errors.Errorf("failed to open process template path %s: %v", r.path, err) } // From this point, log all errors bot continue reading for _, entry := range entries { if entry.IsDir() { continue } if filepath.Ext(entry.Name()) != JSONExt { continue } filePath := filepath.Join(r.path, entry.Name()) file, err := ioutil.ReadFile(filePath) if err != nil { r.log.Errorf("failed to read file %s: %v", filePath, err) continue } template := &process.Template{} if err := json.Unmarshal(file, template); err != nil { r.log.Errorf("failed to unmarshal file %s: %v", filePath, err) continue } templates = append(templates, template) } r.log.Debugf("read %d process template(s)", len(templates)) return templates, nil }
go
func (r *Reader) GetAllTemplates() ([]*process.Template, error) { var templates []*process.Template entries, err := ioutil.ReadDir(r.path) if err != nil { return templates, errors.Errorf("failed to open process template path %s: %v", r.path, err) } // From this point, log all errors bot continue reading for _, entry := range entries { if entry.IsDir() { continue } if filepath.Ext(entry.Name()) != JSONExt { continue } filePath := filepath.Join(r.path, entry.Name()) file, err := ioutil.ReadFile(filePath) if err != nil { r.log.Errorf("failed to read file %s: %v", filePath, err) continue } template := &process.Template{} if err := json.Unmarshal(file, template); err != nil { r.log.Errorf("failed to unmarshal file %s: %v", filePath, err) continue } templates = append(templates, template) } r.log.Debugf("read %d process template(s)", len(templates)) return templates, nil }
[ "func", "(", "r", "*", "Reader", ")", "GetAllTemplates", "(", ")", "(", "[", "]", "*", "process", ".", "Template", ",", "error", ")", "{", "var", "templates", "[", "]", "*", "process", ".", "Template", "\n", "entries", ",", "err", ":=", "ioutil", "...
// GetAllTemplates reads all templates from reader's path. Error is returned if path is not a directory. All JSON // file are read and un-marshaled as template objects
[ "GetAllTemplates", "reads", "all", "templates", "from", "reader", "s", "path", ".", "Error", "is", "returned", "if", "path", "is", "not", "a", "directory", ".", "All", "JSON", "file", "are", "read", "and", "un", "-", "marshaled", "as", "template", "objects...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/template/template.go#L61-L93
4,488
ligato/cn-infra
db/keyval/filedb/decoder/decoder_json.go
Encode
func (jd *JSONDecoder) Encode(data []*FileDataEntry) ([]byte, error) { // Convert to json-specific structure var jsonFileEntries []jsonFileEntry for _, dataEntry := range data { jsonFileEntries = append(jsonFileEntries, jsonFileEntry{ Key: dataEntry.Key, Value: dataEntry.Value, }) } // Encode to type specific structure jsonFile := &jsonFile{Data: jsonFileEntries} return json.Marshal(jsonFile) }
go
func (jd *JSONDecoder) Encode(data []*FileDataEntry) ([]byte, error) { // Convert to json-specific structure var jsonFileEntries []jsonFileEntry for _, dataEntry := range data { jsonFileEntries = append(jsonFileEntries, jsonFileEntry{ Key: dataEntry.Key, Value: dataEntry.Value, }) } // Encode to type specific structure jsonFile := &jsonFile{Data: jsonFileEntries} return json.Marshal(jsonFile) }
[ "func", "(", "jd", "*", "JSONDecoder", ")", "Encode", "(", "data", "[", "]", "*", "FileDataEntry", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Convert to json-specific structure", "var", "jsonFileEntries", "[", "]", "jsonFileEntry", "\n", "for", ...
// Encode provided file entries into JSON byte set
[ "Encode", "provided", "file", "entries", "into", "JSON", "byte", "set" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/decoder/decoder_json.go#L61-L73
4,489
ligato/cn-infra
db/keyval/filedb/decoder/decoder_json.go
Decode
func (jd *JSONDecoder) Decode(byteSet []byte) ([]*FileDataEntry, error) { if len(byteSet) == 0 { return []*FileDataEntry{}, nil } // Decode to type-specific structure jsonFile := jsonFile{} err := json.Unmarshal(byteSet, &jsonFile) if err != nil { return nil, fmt.Errorf("failed to decode json file: %v", err) } // Convert to common file data entry list structure var dataEntries []*FileDataEntry for _, dataEntry := range jsonFile.Data { dataEntries = append(dataEntries, &FileDataEntry{Key: dataEntry.Key, Value: dataEntry.Value}) } return dataEntries, nil }
go
func (jd *JSONDecoder) Decode(byteSet []byte) ([]*FileDataEntry, error) { if len(byteSet) == 0 { return []*FileDataEntry{}, nil } // Decode to type-specific structure jsonFile := jsonFile{} err := json.Unmarshal(byteSet, &jsonFile) if err != nil { return nil, fmt.Errorf("failed to decode json file: %v", err) } // Convert to common file data entry list structure var dataEntries []*FileDataEntry for _, dataEntry := range jsonFile.Data { dataEntries = append(dataEntries, &FileDataEntry{Key: dataEntry.Key, Value: dataEntry.Value}) } return dataEntries, nil }
[ "func", "(", "jd", "*", "JSONDecoder", ")", "Decode", "(", "byteSet", "[", "]", "byte", ")", "(", "[", "]", "*", "FileDataEntry", ",", "error", ")", "{", "if", "len", "(", "byteSet", ")", "==", "0", "{", "return", "[", "]", "*", "FileDataEntry", ...
// Decode provided byte set of json file and returns set of file data entries
[ "Decode", "provided", "byte", "set", "of", "json", "file", "and", "returns", "set", "of", "file", "data", "entries" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/decoder/decoder_json.go#L76-L92
4,490
ligato/cn-infra
messaging/kafka/mux/config.go
ConfigFromFile
func ConfigFromFile(fpath string) (*Config, error) { cfg := &Config{} err := config.ParseConfigFromYamlFile(fpath, cfg) if err != nil { return nil, err } return cfg, err }
go
func ConfigFromFile(fpath string) (*Config, error) { cfg := &Config{} err := config.ParseConfigFromYamlFile(fpath, cfg) if err != nil { return nil, err } return cfg, err }
[ "func", "ConfigFromFile", "(", "fpath", "string", ")", "(", "*", "Config", ",", "error", ")", "{", "cfg", ":=", "&", "Config", "{", "}", "\n", "err", ":=", "config", ".", "ParseConfigFromYamlFile", "(", "fpath", ",", "cfg", ")", "\n", "if", "err", "!...
// ConfigFromFile loads the Kafka multiplexer configuration from the // specified file. If the specified file is valid and contains // valid configuration, the parsed configuration is // returned; otherwise, an error is returned.
[ "ConfigFromFile", "loads", "the", "Kafka", "multiplexer", "configuration", "from", "the", "specified", "file", ".", "If", "the", "specified", "file", "is", "valid", "and", "contains", "valid", "configuration", "the", "parsed", "configuration", "is", "returned", ";...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/config.go#L40-L47
4,491
ligato/cn-infra
messaging/kafka/mux/config.go
InitMultiplexer
func InitMultiplexer(configFile string, name string, log logging.Logger) (*Multiplexer, error) { var err error var tls clienttls.TLS cfg := &Config{[]string{DefAddress}, "", tls} if configFile != "" { cfg, err = ConfigFromFile(configFile) if err != nil { return nil, err } } // prepare client config clientCfg := client.NewConfig(log) clientCfg.SetSendSuccess(true) clientCfg.SetSuccessChan(make(chan *client.ProducerMessage)) clientCfg.SetSendError(true) clientCfg.SetErrorChan(make(chan *client.ProducerError)) clientCfg.SetBrokers(cfg.Addrs...) if cfg.TLS.Enabled { tlsConfig, err := clienttls.CreateTLSConfig(cfg.TLS) if err != nil { return nil, err } clientCfg.SetTLS(tlsConfig) } // create hash client sClientHash, err := client.NewClient(clientCfg, client.Hash) if err != nil { return nil, err } // create manual client sClientManual, err := client.NewClient(clientCfg, client.Manual) if err != nil { return nil, err } // todo client is currently set always as hash return InitMultiplexerWithConfig(clientCfg, sClientHash, sClientManual, name, log) }
go
func InitMultiplexer(configFile string, name string, log logging.Logger) (*Multiplexer, error) { var err error var tls clienttls.TLS cfg := &Config{[]string{DefAddress}, "", tls} if configFile != "" { cfg, err = ConfigFromFile(configFile) if err != nil { return nil, err } } // prepare client config clientCfg := client.NewConfig(log) clientCfg.SetSendSuccess(true) clientCfg.SetSuccessChan(make(chan *client.ProducerMessage)) clientCfg.SetSendError(true) clientCfg.SetErrorChan(make(chan *client.ProducerError)) clientCfg.SetBrokers(cfg.Addrs...) if cfg.TLS.Enabled { tlsConfig, err := clienttls.CreateTLSConfig(cfg.TLS) if err != nil { return nil, err } clientCfg.SetTLS(tlsConfig) } // create hash client sClientHash, err := client.NewClient(clientCfg, client.Hash) if err != nil { return nil, err } // create manual client sClientManual, err := client.NewClient(clientCfg, client.Manual) if err != nil { return nil, err } // todo client is currently set always as hash return InitMultiplexerWithConfig(clientCfg, sClientHash, sClientManual, name, log) }
[ "func", "InitMultiplexer", "(", "configFile", "string", ",", "name", "string", ",", "log", "logging", ".", "Logger", ")", "(", "*", "Multiplexer", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "tls", "clienttls", ".", "TLS", "\n", "cfg", ...
// InitMultiplexer initialize and returns new kafka multiplexer based on the supplied config file. // Name is used as groupId identification of consumer. Kafka allows to store last read offset for // a groupId. This is leveraged to deliver unread messages after restart.
[ "InitMultiplexer", "initialize", "and", "returns", "new", "kafka", "multiplexer", "based", "on", "the", "supplied", "config", "file", ".", "Name", "is", "used", "as", "groupId", "identification", "of", "consumer", ".", "Kafka", "allows", "to", "store", "last", ...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/config.go#L64-L104
4,492
ligato/cn-infra
messaging/kafka/mux/config.go
InitMultiplexerWithConfig
func InitMultiplexerWithConfig(clientCfg *client.Config, hsClient sarama.Client, manClient sarama.Client, name string, log logging.Logger) (*Multiplexer, error) { const errorFmt = "Failed to create Kafka %s, Configured broker(s) %v, Error: '%s'" log.WithField("addrs", hsClient.Brokers()).Debug("Kafka connecting") startTime := time.Now() producers := multiplexerProducers{} // Prepare sync/async producer if hsClient != nil { hashSyncProducer, err := client.NewSyncProducer(clientCfg, hsClient, client.Hash, nil) if err != nil { log.Errorf(errorFmt, "SyncProducer (hash)", clientCfg.Brokers, err) return nil, err } hashAsyncProducer, err := client.NewAsyncProducer(clientCfg, hsClient, client.Hash, nil) if err != nil { log.Errorf(errorFmt, "AsyncProducer", clientCfg.Brokers, err) return nil, err } producers.hashSyncProducer = hashSyncProducer producers.hashAsyncProducer = hashAsyncProducer } // Prepare manual sync/async producer if manClient != nil { manualSyncProducer, err := client.NewSyncProducer(clientCfg, manClient, client.Manual, nil) if err != nil { log.Errorf(errorFmt, "SyncProducer (manual)", clientCfg.Brokers, err) return nil, err } manualAsyncProducer, err := client.NewAsyncProducer(clientCfg, manClient, client.Manual, nil) if err != nil { log.Errorf(errorFmt, "AsyncProducer", clientCfg.Brokers, err) return nil, err } producers.manSyncProducer = manualSyncProducer producers.manAsyncProducer = manualAsyncProducer } kafkaConnect := time.Since(startTime) log.WithField("durationInNs", kafkaConnect.Nanoseconds()).Info("Connecting to kafka took ", kafkaConnect) return NewMultiplexer(getConsumerFactory(clientCfg), producers, clientCfg, name, log), nil }
go
func InitMultiplexerWithConfig(clientCfg *client.Config, hsClient sarama.Client, manClient sarama.Client, name string, log logging.Logger) (*Multiplexer, error) { const errorFmt = "Failed to create Kafka %s, Configured broker(s) %v, Error: '%s'" log.WithField("addrs", hsClient.Brokers()).Debug("Kafka connecting") startTime := time.Now() producers := multiplexerProducers{} // Prepare sync/async producer if hsClient != nil { hashSyncProducer, err := client.NewSyncProducer(clientCfg, hsClient, client.Hash, nil) if err != nil { log.Errorf(errorFmt, "SyncProducer (hash)", clientCfg.Brokers, err) return nil, err } hashAsyncProducer, err := client.NewAsyncProducer(clientCfg, hsClient, client.Hash, nil) if err != nil { log.Errorf(errorFmt, "AsyncProducer", clientCfg.Brokers, err) return nil, err } producers.hashSyncProducer = hashSyncProducer producers.hashAsyncProducer = hashAsyncProducer } // Prepare manual sync/async producer if manClient != nil { manualSyncProducer, err := client.NewSyncProducer(clientCfg, manClient, client.Manual, nil) if err != nil { log.Errorf(errorFmt, "SyncProducer (manual)", clientCfg.Brokers, err) return nil, err } manualAsyncProducer, err := client.NewAsyncProducer(clientCfg, manClient, client.Manual, nil) if err != nil { log.Errorf(errorFmt, "AsyncProducer", clientCfg.Brokers, err) return nil, err } producers.manSyncProducer = manualSyncProducer producers.manAsyncProducer = manualAsyncProducer } kafkaConnect := time.Since(startTime) log.WithField("durationInNs", kafkaConnect.Nanoseconds()).Info("Connecting to kafka took ", kafkaConnect) return NewMultiplexer(getConsumerFactory(clientCfg), producers, clientCfg, name, log), nil }
[ "func", "InitMultiplexerWithConfig", "(", "clientCfg", "*", "client", ".", "Config", ",", "hsClient", "sarama", ".", "Client", ",", "manClient", "sarama", ".", "Client", ",", "name", "string", ",", "log", "logging", ".", "Logger", ")", "(", "*", "Multiplexer...
// InitMultiplexerWithConfig initialize and returns new kafka multiplexer based on the supplied mux configuration. // Name is used as groupId identification of consumer. Kafka allows to store last read offset for a groupId. // This is leveraged to deliver unread messages after restart.
[ "InitMultiplexerWithConfig", "initialize", "and", "returns", "new", "kafka", "multiplexer", "based", "on", "the", "supplied", "mux", "configuration", ".", "Name", "is", "used", "as", "groupId", "identification", "of", "consumer", ".", "Kafka", "allows", "to", "sto...
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/mux/config.go#L109-L153
4,493
ligato/cn-infra
examples/consul-lib/main.go
listKeys
func listKeys(db keyval.ProtoBroker) { resp, err := db.ListKeys(phonebook.EtcdPath()) if err != nil { log.Fatal(err) } fmt.Println("list keys:") for { key, _, stop := resp.GetNext() if stop { break } fmt.Printf("- %s\n", key) } }
go
func listKeys(db keyval.ProtoBroker) { resp, err := db.ListKeys(phonebook.EtcdPath()) if err != nil { log.Fatal(err) } fmt.Println("list keys:") for { key, _, stop := resp.GetNext() if stop { break } fmt.Printf("- %s\n", key) } }
[ "func", "listKeys", "(", "db", "keyval", ".", "ProtoBroker", ")", "{", "resp", ",", "err", ":=", "db", ".", "ListKeys", "(", "phonebook", ".", "EtcdPath", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "...
// listKeys lists keys
[ "listKeys", "lists", "keys" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/consul-lib/main.go#L53-L69
4,494
ligato/cn-infra
examples/consul-lib/main.go
list
func list(db keyval.ProtoBroker) { resp, err := db.ListValues(phonebook.EtcdPath()) if err != nil { log.Fatal(err) } var revision int64 fmt.Println("list values:") for { c := &phonebook.Contact{} kv, stop := resp.GetNext() if stop { break } if kv.GetRevision() > revision { revision = kv.GetRevision() } err = kv.GetValue(c) if err != nil { log.Fatal(err) } fmt.Printf("\t%s\n\t\t%s\n\t\t%s\n", c.Name, c.Company, c.Phonenumber) } fmt.Println("Revision", revision) }
go
func list(db keyval.ProtoBroker) { resp, err := db.ListValues(phonebook.EtcdPath()) if err != nil { log.Fatal(err) } var revision int64 fmt.Println("list values:") for { c := &phonebook.Contact{} kv, stop := resp.GetNext() if stop { break } if kv.GetRevision() > revision { revision = kv.GetRevision() } err = kv.GetValue(c) if err != nil { log.Fatal(err) } fmt.Printf("\t%s\n\t\t%s\n\t\t%s\n", c.Name, c.Company, c.Phonenumber) } fmt.Println("Revision", revision) }
[ "func", "list", "(", "db", "keyval", ".", "ProtoBroker", ")", "{", "resp", ",", "err", ":=", "db", ".", "ListValues", "(", "phonebook", ".", "EtcdPath", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n...
// list lists keys with values
[ "list", "lists", "keys", "with", "values" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/consul-lib/main.go#L72-L98
4,495
ligato/cn-infra
examples/consul-lib/main.go
put
func put(db keyval.ProtoBroker, data []string) { c := &phonebook.Contact{Name: data[0], Company: data[1], Phonenumber: data[2]} key := phonebook.EtcdContactPath(c) err := db.Put(key, c) if err != nil { log.Fatal(err) } fmt.Println("Saved:", key) }
go
func put(db keyval.ProtoBroker, data []string) { c := &phonebook.Contact{Name: data[0], Company: data[1], Phonenumber: data[2]} key := phonebook.EtcdContactPath(c) err := db.Put(key, c) if err != nil { log.Fatal(err) } fmt.Println("Saved:", key) }
[ "func", "put", "(", "db", "keyval", ".", "ProtoBroker", ",", "data", "[", "]", "string", ")", "{", "c", ":=", "&", "phonebook", ".", "Contact", "{", "Name", ":", "data", "[", "0", "]", ",", "Company", ":", "data", "[", "1", "]", ",", "Phonenumber...
// put saves single entry
[ "put", "saves", "single", "entry" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/consul-lib/main.go#L101-L112
4,496
ligato/cn-infra
examples/consul-lib/main.go
get
func get(db keyval.ProtoBroker, data string) { c := &phonebook.Contact{Name: data} key := phonebook.EtcdContactPath(c) found, _, err := db.GetValue(key, c) if err != nil { log.Fatal(err) } else if !found { fmt.Println("Not found") return } fmt.Println("Loaded:", key, c) }
go
func get(db keyval.ProtoBroker, data string) { c := &phonebook.Contact{Name: data} key := phonebook.EtcdContactPath(c) found, _, err := db.GetValue(key, c) if err != nil { log.Fatal(err) } else if !found { fmt.Println("Not found") return } fmt.Println("Loaded:", key, c) }
[ "func", "get", "(", "db", "keyval", ".", "ProtoBroker", ",", "data", "string", ")", "{", "c", ":=", "&", "phonebook", ".", "Contact", "{", "Name", ":", "data", "}", "\n\n", "key", ":=", "phonebook", ".", "EtcdContactPath", "(", "c", ")", "\n\n", "fou...
// get retrieves single entry
[ "get", "retrieves", "single", "entry" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/consul-lib/main.go#L115-L129
4,497
ligato/cn-infra
examples/consul-lib/main.go
del
func del(db keyval.ProtoBroker, data string) { c := &phonebook.Contact{Name: data} key := phonebook.EtcdContactPath(c) existed, err := db.Delete(key) if err != nil { log.Fatal(err) } else if !existed { fmt.Println("Not existed") return } fmt.Println("Deleted:", key) }
go
func del(db keyval.ProtoBroker, data string) { c := &phonebook.Contact{Name: data} key := phonebook.EtcdContactPath(c) existed, err := db.Delete(key) if err != nil { log.Fatal(err) } else if !existed { fmt.Println("Not existed") return } fmt.Println("Deleted:", key) }
[ "func", "del", "(", "db", "keyval", ".", "ProtoBroker", ",", "data", "string", ")", "{", "c", ":=", "&", "phonebook", ".", "Contact", "{", "Name", ":", "data", "}", "\n\n", "key", ":=", "phonebook", ".", "EtcdContactPath", "(", "c", ")", "\n\n", "exi...
// del deletes single entry
[ "del", "deletes", "single", "entry" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/consul-lib/main.go#L132-L146
4,498
ligato/cn-infra
messaging/kafka/client/syncproducer.go
SendMsgByte
func (ref *SyncProducer) SendMsgByte(topic string, key []byte, msg []byte) (*ProducerMessage, error) { // generate a key if none supplied (used by hash partitioner) ref.WithFields(logging.Fields{"key": key, "msg": msg}).Debug("Sending") if key == nil || len(key) == 0 { md5Sum := fmt.Sprintf("%x", md5.Sum(msg)) return ref.SendMsgToPartition(topic, ref.Partition, sarama.ByteEncoder(md5Sum), sarama.ByteEncoder(msg)) } return ref.SendMsgToPartition(topic, ref.Partition, sarama.ByteEncoder(key), sarama.ByteEncoder(msg)) }
go
func (ref *SyncProducer) SendMsgByte(topic string, key []byte, msg []byte) (*ProducerMessage, error) { // generate a key if none supplied (used by hash partitioner) ref.WithFields(logging.Fields{"key": key, "msg": msg}).Debug("Sending") if key == nil || len(key) == 0 { md5Sum := fmt.Sprintf("%x", md5.Sum(msg)) return ref.SendMsgToPartition(topic, ref.Partition, sarama.ByteEncoder(md5Sum), sarama.ByteEncoder(msg)) } return ref.SendMsgToPartition(topic, ref.Partition, sarama.ByteEncoder(key), sarama.ByteEncoder(msg)) }
[ "func", "(", "ref", "*", "SyncProducer", ")", "SendMsgByte", "(", "topic", "string", ",", "key", "[", "]", "byte", ",", "msg", "[", "]", "byte", ")", "(", "*", "ProducerMessage", ",", "error", ")", "{", "// generate a key if none supplied (used by hash partiti...
// SendMsgByte sends a message to Kafka
[ "SendMsgByte", "sends", "a", "message", "to", "Kafka" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/syncproducer.go#L142-L151
4,499
ligato/cn-infra
messaging/kafka/client/syncproducer.go
SendMsgToPartition
func (ref *SyncProducer) SendMsgToPartition(topic string, partition int32, key sarama.Encoder, msg sarama.Encoder) (*ProducerMessage, error) { if msg == nil { err := errors.New("nil message can not be sent") ref.Error(err) return nil, err } message := &sarama.ProducerMessage{ Topic: topic, Partition: partition, Value: msg, Key: key, } partition, offset, err := ref.Producer.SendMessage(message) pmsg := &ProducerMessage{ Topic: message.Topic, Key: message.Key, Value: message.Value, Metadata: message.Metadata, Offset: offset, Partition: partition, } if err != nil { return pmsg, err } ref.Debugf("message sent: %s", pmsg) return pmsg, nil }
go
func (ref *SyncProducer) SendMsgToPartition(topic string, partition int32, key sarama.Encoder, msg sarama.Encoder) (*ProducerMessage, error) { if msg == nil { err := errors.New("nil message can not be sent") ref.Error(err) return nil, err } message := &sarama.ProducerMessage{ Topic: topic, Partition: partition, Value: msg, Key: key, } partition, offset, err := ref.Producer.SendMessage(message) pmsg := &ProducerMessage{ Topic: message.Topic, Key: message.Key, Value: message.Value, Metadata: message.Metadata, Offset: offset, Partition: partition, } if err != nil { return pmsg, err } ref.Debugf("message sent: %s", pmsg) return pmsg, nil }
[ "func", "(", "ref", "*", "SyncProducer", ")", "SendMsgToPartition", "(", "topic", "string", ",", "partition", "int32", ",", "key", "sarama", ".", "Encoder", ",", "msg", "sarama", ".", "Encoder", ")", "(", "*", "ProducerMessage", ",", "error", ")", "{", "...
// SendMsgToPartition sends a message to Kafka
[ "SendMsgToPartition", "sends", "a", "message", "to", "Kafka" ]
6552f4407e293b0986ec353eb0f01968cbecb928
https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/syncproducer.go#L154-L182