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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
12,600 | FDio/govpp | extras/libmemif/packethandle.go | WritePacketData | func (handle *MemifPacketHandle) WritePacketData(data []byte) (err error) {
handle.writeMu.Lock()
defer handle.writeMu.Unlock()
if handle.stop {
err = io.EOF
return
}
count, err := handle.memif.TxBurst(handle.queueId, []RawPacketData{data})
if err != nil {
return
}
if count == 0 {
err = io.EOF
}
return
} | go | func (handle *MemifPacketHandle) WritePacketData(data []byte) (err error) {
handle.writeMu.Lock()
defer handle.writeMu.Unlock()
if handle.stop {
err = io.EOF
return
}
count, err := handle.memif.TxBurst(handle.queueId, []RawPacketData{data})
if err != nil {
return
}
if count == 0 {
err = io.EOF
}
return
} | [
"func",
"(",
"handle",
"*",
"MemifPacketHandle",
")",
"WritePacketData",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"handle",
".",
"writeMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"handle",
".",
"writeMu",
".",
"Unlock",
"(",
... | // Writes packet data to memif in burst of 1 packet. In case no packet is sent, this method throws io.EOF error and
// called should stop trying to write packets. | [
"Writes",
"packet",
"data",
"to",
"memif",
"in",
"burst",
"of",
"1",
"packet",
".",
"In",
"case",
"no",
"packet",
"is",
"sent",
"this",
"method",
"throws",
"io",
".",
"EOF",
"error",
"and",
"called",
"should",
"stop",
"trying",
"to",
"write",
"packets",
... | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/packethandle.go#L112-L132 |
12,601 | FDio/govpp | extras/libmemif/packethandle.go | Close | func (handle *MemifPacketHandle) Close() {
handle.closeMu.Lock()
defer handle.closeMu.Unlock()
// wait for packet reader to stop
handle.readMu.Lock()
defer handle.readMu.Unlock()
// wait for packet writer to stop
handle.writeMu.Lock()
defer handle.writeMu.Unlock()
// stop reading and writing
handle.stop = true
} | go | func (handle *MemifPacketHandle) Close() {
handle.closeMu.Lock()
defer handle.closeMu.Unlock()
// wait for packet reader to stop
handle.readMu.Lock()
defer handle.readMu.Unlock()
// wait for packet writer to stop
handle.writeMu.Lock()
defer handle.writeMu.Unlock()
// stop reading and writing
handle.stop = true
} | [
"func",
"(",
"handle",
"*",
"MemifPacketHandle",
")",
"Close",
"(",
")",
"{",
"handle",
".",
"closeMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"handle",
".",
"closeMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// wait for packet reader to stop",
"handle",
".",
"re... | // Waits for all read and write operations to finish and then prevents more from occurring. Handle can be closed only
// once and then can never be opened again. | [
"Waits",
"for",
"all",
"read",
"and",
"write",
"operations",
"to",
"finish",
"and",
"then",
"prevents",
"more",
"from",
"occurring",
".",
"Handle",
"can",
"be",
"closed",
"only",
"once",
"and",
"then",
"can",
"never",
"be",
"opened",
"again",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/packethandle.go#L136-L150 |
12,602 | FDio/govpp | api/binapi.go | RegisterMessage | func RegisterMessage(x Message, name string) {
name = x.GetMessageName() + "_" + x.GetCrcString()
/*if _, ok := registeredMessages[name]; ok {
panic(fmt.Errorf("govpp: duplicate message registered: %s (%s)", name, x.GetCrcString()))
}*/
registeredMessages[name] = x
} | go | func RegisterMessage(x Message, name string) {
name = x.GetMessageName() + "_" + x.GetCrcString()
/*if _, ok := registeredMessages[name]; ok {
panic(fmt.Errorf("govpp: duplicate message registered: %s (%s)", name, x.GetCrcString()))
}*/
registeredMessages[name] = x
} | [
"func",
"RegisterMessage",
"(",
"x",
"Message",
",",
"name",
"string",
")",
"{",
"name",
"=",
"x",
".",
"GetMessageName",
"(",
")",
"+",
"\"",
"\"",
"+",
"x",
".",
"GetCrcString",
"(",
")",
"\n",
"/*if _, ok := registeredMessages[name]; ok {\n\t\tpanic(fmt.Error... | // RegisterMessage is called from generated code to register message. | [
"RegisterMessage",
"is",
"called",
"from",
"generated",
"code",
"to",
"register",
"message",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/api/binapi.go#L124-L130 |
12,603 | FDio/govpp | core/stats.go | ConnectStats | func ConnectStats(stats adapter.StatsAPI) (*StatsConnection, error) {
c := newStatsConnection(stats)
if err := c.connectClient(); err != nil {
return nil, err
}
return c, nil
} | go | func ConnectStats(stats adapter.StatsAPI) (*StatsConnection, error) {
c := newStatsConnection(stats)
if err := c.connectClient(); err != nil {
return nil, err
}
return c, nil
} | [
"func",
"ConnectStats",
"(",
"stats",
"adapter",
".",
"StatsAPI",
")",
"(",
"*",
"StatsConnection",
",",
"error",
")",
"{",
"c",
":=",
"newStatsConnection",
"(",
"stats",
")",
"\n\n",
"if",
"err",
":=",
"c",
".",
"connectClient",
"(",
")",
";",
"err",
... | // Connect connects to Stats API using specified adapter and returns a connection handle.
// This call blocks until it is either connected, or an error occurs.
// Only one connection attempt will be performed. | [
"Connect",
"connects",
"to",
"Stats",
"API",
"using",
"specified",
"adapter",
"and",
"returns",
"a",
"connection",
"handle",
".",
"This",
"call",
"blocks",
"until",
"it",
"is",
"either",
"connected",
"or",
"an",
"error",
"occurs",
".",
"Only",
"one",
"connec... | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L78-L86 |
12,604 | FDio/govpp | core/stats.go | Disconnect | func (c *StatsConnection) Disconnect() {
if c == nil {
return
}
if c.statsClient != nil {
c.disconnectClient()
}
} | go | func (c *StatsConnection) Disconnect() {
if c == nil {
return
}
if c.statsClient != nil {
c.disconnectClient()
}
} | [
"func",
"(",
"c",
"*",
"StatsConnection",
")",
"Disconnect",
"(",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"statsClient",
"!=",
"nil",
"{",
"c",
".",
"disconnectClient",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Disconnect disconnects from Stats API and releases all connection-related resources. | [
"Disconnect",
"disconnects",
"from",
"Stats",
"API",
"and",
"releases",
"all",
"connection",
"-",
"related",
"resources",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L104-L112 |
12,605 | FDio/govpp | core/stats.go | GetSystemStats | func (c *StatsConnection) GetSystemStats() (*api.SystemStats, error) {
stats, err := c.statsClient.DumpStats(SystemStatsPrefix)
if err != nil {
return nil, err
}
sysStats := &api.SystemStats{}
for _, stat := range stats {
switch stat.Name {
case SystemStats_VectorRate:
sysStats.VectorRate = scalarStatToFloat64(stat.Data)
case SystemStats_InputRate:
sysStats.InputRate = scalarStatToFloat64(stat.Data)
case SystemStats_LastUpdate:
sysStats.LastUpdate = scalarStatToFloat64(stat.Data)
case SystemStats_LastStatsClear:
sysStats.LastStatsClear = scalarStatToFloat64(stat.Data)
case SystemStats_Heartbeat:
sysStats.Heartbeat = scalarStatToFloat64(stat.Data)
}
}
return sysStats, nil
} | go | func (c *StatsConnection) GetSystemStats() (*api.SystemStats, error) {
stats, err := c.statsClient.DumpStats(SystemStatsPrefix)
if err != nil {
return nil, err
}
sysStats := &api.SystemStats{}
for _, stat := range stats {
switch stat.Name {
case SystemStats_VectorRate:
sysStats.VectorRate = scalarStatToFloat64(stat.Data)
case SystemStats_InputRate:
sysStats.InputRate = scalarStatToFloat64(stat.Data)
case SystemStats_LastUpdate:
sysStats.LastUpdate = scalarStatToFloat64(stat.Data)
case SystemStats_LastStatsClear:
sysStats.LastStatsClear = scalarStatToFloat64(stat.Data)
case SystemStats_Heartbeat:
sysStats.Heartbeat = scalarStatToFloat64(stat.Data)
}
}
return sysStats, nil
} | [
"func",
"(",
"c",
"*",
"StatsConnection",
")",
"GetSystemStats",
"(",
")",
"(",
"*",
"api",
".",
"SystemStats",
",",
"error",
")",
"{",
"stats",
",",
"err",
":=",
"c",
".",
"statsClient",
".",
"DumpStats",
"(",
"SystemStatsPrefix",
")",
"\n",
"if",
"er... | // GetSystemStats retrieves VPP system stats. | [
"GetSystemStats",
"retrieves",
"VPP",
"system",
"stats",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L121-L145 |
12,606 | FDio/govpp | core/stats.go | GetErrorStats | func (c *StatsConnection) GetErrorStats(names ...string) (*api.ErrorStats, error) {
var patterns []string
if len(names) > 0 {
patterns = make([]string, len(names))
for i, name := range names {
patterns[i] = CounterStatsPrefix + name
}
} else {
// retrieve all error counters by default
patterns = []string{CounterStatsPrefix}
}
stats, err := c.statsClient.DumpStats(patterns...)
if err != nil {
return nil, err
}
var errorStats = &api.ErrorStats{}
for _, stat := range stats {
statName := strings.TrimPrefix(stat.Name, CounterStatsPrefix)
/* TODO: deal with stats that contain '/' in node/counter name
parts := strings.Split(statName, "/")
var nodeName, counterName string
switch len(parts) {
case 2:
nodeName = parts[0]
counterName = parts[1]
case 3:
nodeName = parts[0] + parts[1]
counterName = parts[2]
}*/
errorStats.Errors = append(errorStats.Errors, api.ErrorCounter{
CounterName: statName,
Value: errorStatToUint64(stat.Data),
})
}
return errorStats, nil
} | go | func (c *StatsConnection) GetErrorStats(names ...string) (*api.ErrorStats, error) {
var patterns []string
if len(names) > 0 {
patterns = make([]string, len(names))
for i, name := range names {
patterns[i] = CounterStatsPrefix + name
}
} else {
// retrieve all error counters by default
patterns = []string{CounterStatsPrefix}
}
stats, err := c.statsClient.DumpStats(patterns...)
if err != nil {
return nil, err
}
var errorStats = &api.ErrorStats{}
for _, stat := range stats {
statName := strings.TrimPrefix(stat.Name, CounterStatsPrefix)
/* TODO: deal with stats that contain '/' in node/counter name
parts := strings.Split(statName, "/")
var nodeName, counterName string
switch len(parts) {
case 2:
nodeName = parts[0]
counterName = parts[1]
case 3:
nodeName = parts[0] + parts[1]
counterName = parts[2]
}*/
errorStats.Errors = append(errorStats.Errors, api.ErrorCounter{
CounterName: statName,
Value: errorStatToUint64(stat.Data),
})
}
return errorStats, nil
} | [
"func",
"(",
"c",
"*",
"StatsConnection",
")",
"GetErrorStats",
"(",
"names",
"...",
"string",
")",
"(",
"*",
"api",
".",
"ErrorStats",
",",
"error",
")",
"{",
"var",
"patterns",
"[",
"]",
"string",
"\n",
"if",
"len",
"(",
"names",
")",
">",
"0",
"... | // GetErrorStats retrieves VPP error stats. | [
"GetErrorStats",
"retrieves",
"VPP",
"error",
"stats",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L148-L188 |
12,607 | FDio/govpp | core/stats.go | GetNodeStats | func (c *StatsConnection) GetNodeStats() (*api.NodeStats, error) {
stats, err := c.statsClient.DumpStats(NodeStatsPrefix)
if err != nil {
return nil, err
}
nodeStats := &api.NodeStats{}
var setPerNode = func(perNode []uint64, fn func(c *api.NodeCounters, v uint64)) {
if nodeStats.Nodes == nil {
nodeStats.Nodes = make([]api.NodeCounters, len(perNode))
for i := range perNode {
nodeStats.Nodes[i].NodeIndex = uint32(i)
}
}
for i, v := range perNode {
if len(nodeStats.Nodes) <= i {
break
}
nodeCounters := nodeStats.Nodes[i]
fn(&nodeCounters, v)
nodeStats.Nodes[i] = nodeCounters
}
}
for _, stat := range stats {
switch stat.Name {
case NodeStats_Names:
if names, ok := stat.Data.(adapter.NameStat); !ok {
return nil, fmt.Errorf("invalid stat type for %s", stat.Name)
} else {
if nodeStats.Nodes == nil {
nodeStats.Nodes = make([]api.NodeCounters, len(names))
for i := range names {
nodeStats.Nodes[i].NodeIndex = uint32(i)
}
}
for i, name := range names {
nodeStats.Nodes[i].NodeName = string(name)
}
}
case NodeStats_Clocks:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Clocks = v
})
case NodeStats_Vectors:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Vectors = v
})
case NodeStats_Calls:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Calls = v
})
case NodeStats_Suspends:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Suspends = v
})
}
}
return nodeStats, nil
} | go | func (c *StatsConnection) GetNodeStats() (*api.NodeStats, error) {
stats, err := c.statsClient.DumpStats(NodeStatsPrefix)
if err != nil {
return nil, err
}
nodeStats := &api.NodeStats{}
var setPerNode = func(perNode []uint64, fn func(c *api.NodeCounters, v uint64)) {
if nodeStats.Nodes == nil {
nodeStats.Nodes = make([]api.NodeCounters, len(perNode))
for i := range perNode {
nodeStats.Nodes[i].NodeIndex = uint32(i)
}
}
for i, v := range perNode {
if len(nodeStats.Nodes) <= i {
break
}
nodeCounters := nodeStats.Nodes[i]
fn(&nodeCounters, v)
nodeStats.Nodes[i] = nodeCounters
}
}
for _, stat := range stats {
switch stat.Name {
case NodeStats_Names:
if names, ok := stat.Data.(adapter.NameStat); !ok {
return nil, fmt.Errorf("invalid stat type for %s", stat.Name)
} else {
if nodeStats.Nodes == nil {
nodeStats.Nodes = make([]api.NodeCounters, len(names))
for i := range names {
nodeStats.Nodes[i].NodeIndex = uint32(i)
}
}
for i, name := range names {
nodeStats.Nodes[i].NodeName = string(name)
}
}
case NodeStats_Clocks:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Clocks = v
})
case NodeStats_Vectors:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Vectors = v
})
case NodeStats_Calls:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Calls = v
})
case NodeStats_Suspends:
setPerNode(reduceSimpleCounterStat(stat.Data), func(c *api.NodeCounters, v uint64) {
c.Suspends = v
})
}
}
return nodeStats, nil
} | [
"func",
"(",
"c",
"*",
"StatsConnection",
")",
"GetNodeStats",
"(",
")",
"(",
"*",
"api",
".",
"NodeStats",
",",
"error",
")",
"{",
"stats",
",",
"err",
":=",
"c",
".",
"statsClient",
".",
"DumpStats",
"(",
"NodeStatsPrefix",
")",
"\n",
"if",
"err",
... | // GetNodeStats retrieves VPP per node stats. | [
"GetNodeStats",
"retrieves",
"VPP",
"per",
"node",
"stats",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L191-L252 |
12,608 | FDio/govpp | core/stats.go | GetBufferStats | func (c *StatsConnection) GetBufferStats() (*api.BufferStats, error) {
stats, err := c.statsClient.DumpStats(BufferStatsPrefix)
if err != nil {
return nil, err
}
bufStats := &api.BufferStats{
Buffer: map[string]api.BufferPool{},
}
for _, stat := range stats {
d, f := path.Split(stat.Name)
d = strings.TrimSuffix(d, "/")
name := strings.TrimPrefix(d, BufferStatsPrefix)
b, ok := bufStats.Buffer[name]
if !ok {
b.PoolName = name
}
switch f {
case BufferStats_Cached:
b.Cached = scalarStatToFloat64(stat.Data)
case BufferStats_Used:
b.Used = scalarStatToFloat64(stat.Data)
case BufferStats_Available:
b.Available = scalarStatToFloat64(stat.Data)
}
bufStats.Buffer[name] = b
}
return bufStats, nil
} | go | func (c *StatsConnection) GetBufferStats() (*api.BufferStats, error) {
stats, err := c.statsClient.DumpStats(BufferStatsPrefix)
if err != nil {
return nil, err
}
bufStats := &api.BufferStats{
Buffer: map[string]api.BufferPool{},
}
for _, stat := range stats {
d, f := path.Split(stat.Name)
d = strings.TrimSuffix(d, "/")
name := strings.TrimPrefix(d, BufferStatsPrefix)
b, ok := bufStats.Buffer[name]
if !ok {
b.PoolName = name
}
switch f {
case BufferStats_Cached:
b.Cached = scalarStatToFloat64(stat.Data)
case BufferStats_Used:
b.Used = scalarStatToFloat64(stat.Data)
case BufferStats_Available:
b.Available = scalarStatToFloat64(stat.Data)
}
bufStats.Buffer[name] = b
}
return bufStats, nil
} | [
"func",
"(",
"c",
"*",
"StatsConnection",
")",
"GetBufferStats",
"(",
")",
"(",
"*",
"api",
".",
"BufferStats",
",",
"error",
")",
"{",
"stats",
",",
"err",
":=",
"c",
".",
"statsClient",
".",
"DumpStats",
"(",
"BufferStatsPrefix",
")",
"\n",
"if",
"er... | // GetBufferStats retrieves VPP buffer pools stats. | [
"GetBufferStats",
"retrieves",
"VPP",
"buffer",
"pools",
"stats",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/stats.go#L399-L432 |
12,609 | FDio/govpp | codec/msg_codec.go | EncodeMsg | func (*MsgCodec) EncodeMsg(msg api.Message, msgID uint16) (data []byte, err error) {
if msg == nil {
return nil, errors.New("nil message passed in")
}
// try to recover panic which might possibly occur in struc.Pack call
defer func() {
if r := recover(); r != nil {
var ok bool
if err, ok = r.(error); !ok {
err = fmt.Errorf("%v", r)
}
err = fmt.Errorf("panic occurred: %v", err)
}
}()
var header interface{}
// encode message header
switch msg.GetMessageType() {
case api.RequestMessage:
header = &VppRequestHeader{VlMsgID: msgID}
case api.ReplyMessage:
header = &VppReplyHeader{VlMsgID: msgID}
case api.EventMessage:
header = &VppEventHeader{VlMsgID: msgID}
default:
header = &VppOtherHeader{VlMsgID: msgID}
}
buf := new(bytes.Buffer)
// encode message header
if err := struc.Pack(buf, header); err != nil {
return nil, fmt.Errorf("failed to encode message header: %+v, error: %v", header, err)
}
// encode message content
if reflect.TypeOf(msg).Elem().NumField() > 0 {
if err := struc.Pack(buf, msg); err != nil {
return nil, fmt.Errorf("failed to encode message data: %+v, error: %v", data, err)
}
}
return buf.Bytes(), nil
} | go | func (*MsgCodec) EncodeMsg(msg api.Message, msgID uint16) (data []byte, err error) {
if msg == nil {
return nil, errors.New("nil message passed in")
}
// try to recover panic which might possibly occur in struc.Pack call
defer func() {
if r := recover(); r != nil {
var ok bool
if err, ok = r.(error); !ok {
err = fmt.Errorf("%v", r)
}
err = fmt.Errorf("panic occurred: %v", err)
}
}()
var header interface{}
// encode message header
switch msg.GetMessageType() {
case api.RequestMessage:
header = &VppRequestHeader{VlMsgID: msgID}
case api.ReplyMessage:
header = &VppReplyHeader{VlMsgID: msgID}
case api.EventMessage:
header = &VppEventHeader{VlMsgID: msgID}
default:
header = &VppOtherHeader{VlMsgID: msgID}
}
buf := new(bytes.Buffer)
// encode message header
if err := struc.Pack(buf, header); err != nil {
return nil, fmt.Errorf("failed to encode message header: %+v, error: %v", header, err)
}
// encode message content
if reflect.TypeOf(msg).Elem().NumField() > 0 {
if err := struc.Pack(buf, msg); err != nil {
return nil, fmt.Errorf("failed to encode message data: %+v, error: %v", data, err)
}
}
return buf.Bytes(), nil
} | [
"func",
"(",
"*",
"MsgCodec",
")",
"EncodeMsg",
"(",
"msg",
"api",
".",
"Message",
",",
"msgID",
"uint16",
")",
"(",
"data",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"if",
"msg",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New... | // EncodeMsg encodes provided `Message` structure into its binary-encoded data representation. | [
"EncodeMsg",
"encodes",
"provided",
"Message",
"structure",
"into",
"its",
"binary",
"-",
"encoded",
"data",
"representation",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/codec/msg_codec.go#L56-L101 |
12,610 | FDio/govpp | codec/msg_codec.go | DecodeMsg | func (*MsgCodec) DecodeMsg(data []byte, msg api.Message) error {
if msg == nil {
return errors.New("nil message passed in")
}
var header interface{}
// check which header is expected
switch msg.GetMessageType() {
case api.RequestMessage:
header = new(VppRequestHeader)
case api.ReplyMessage:
header = new(VppReplyHeader)
case api.EventMessage:
header = new(VppEventHeader)
default:
header = new(VppOtherHeader)
}
buf := bytes.NewReader(data)
// decode message header
if err := struc.Unpack(buf, header); err != nil {
return fmt.Errorf("failed to decode message header: %+v, error: %v", header, err)
}
// decode message content
if err := struc.Unpack(buf, msg); err != nil {
return fmt.Errorf("failed to decode message data: %+v, error: %v", data, err)
}
return nil
} | go | func (*MsgCodec) DecodeMsg(data []byte, msg api.Message) error {
if msg == nil {
return errors.New("nil message passed in")
}
var header interface{}
// check which header is expected
switch msg.GetMessageType() {
case api.RequestMessage:
header = new(VppRequestHeader)
case api.ReplyMessage:
header = new(VppReplyHeader)
case api.EventMessage:
header = new(VppEventHeader)
default:
header = new(VppOtherHeader)
}
buf := bytes.NewReader(data)
// decode message header
if err := struc.Unpack(buf, header); err != nil {
return fmt.Errorf("failed to decode message header: %+v, error: %v", header, err)
}
// decode message content
if err := struc.Unpack(buf, msg); err != nil {
return fmt.Errorf("failed to decode message data: %+v, error: %v", data, err)
}
return nil
} | [
"func",
"(",
"*",
"MsgCodec",
")",
"DecodeMsg",
"(",
"data",
"[",
"]",
"byte",
",",
"msg",
"api",
".",
"Message",
")",
"error",
"{",
"if",
"msg",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
... | // DecodeMsg decodes binary-encoded data of a message into provided `Message` structure. | [
"DecodeMsg",
"decodes",
"binary",
"-",
"encoded",
"data",
"of",
"a",
"message",
"into",
"provided",
"Message",
"structure",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/codec/msg_codec.go#L104-L136 |
12,611 | FDio/govpp | adapter/mock/binapi/binapi_reflect.go | findFieldOfType | func findFieldOfType(reply reflect.Type, fieldName string) (reflect.StructField, bool) {
for reply.Kind() == reflect.Ptr {
reply = reply.Elem()
}
if reply.Kind() == reflect.Struct {
field, found := reply.FieldByName(fieldName)
return field, found
}
return reflect.StructField{}, false
} | go | func findFieldOfType(reply reflect.Type, fieldName string) (reflect.StructField, bool) {
for reply.Kind() == reflect.Ptr {
reply = reply.Elem()
}
if reply.Kind() == reflect.Struct {
field, found := reply.FieldByName(fieldName)
return field, found
}
return reflect.StructField{}, false
} | [
"func",
"findFieldOfType",
"(",
"reply",
"reflect",
".",
"Type",
",",
"fieldName",
"string",
")",
"(",
"reflect",
".",
"StructField",
",",
"bool",
")",
"{",
"for",
"reply",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"reply",
"=",
"reply",... | // findFieldOfType finds the field specified by its name in provided message defined as reflect.Type data type. | [
"findFieldOfType",
"finds",
"the",
"field",
"specified",
"by",
"its",
"name",
"in",
"provided",
"message",
"defined",
"as",
"reflect",
".",
"Type",
"data",
"type",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/binapi/binapi_reflect.go#L28-L37 |
12,612 | FDio/govpp | adapter/mock/binapi/binapi_reflect.go | findFieldOfValue | func findFieldOfValue(reply reflect.Value, fieldName string) (reflect.Value, bool) {
if reply.Kind() == reflect.Struct {
field := reply.FieldByName(fieldName)
return field, field.IsValid()
} else if reply.Kind() == reflect.Ptr && reply.Elem().Kind() == reflect.Struct {
field := reply.Elem().FieldByName(fieldName)
return field, field.IsValid()
}
return reflect.Value{}, false
} | go | func findFieldOfValue(reply reflect.Value, fieldName string) (reflect.Value, bool) {
if reply.Kind() == reflect.Struct {
field := reply.FieldByName(fieldName)
return field, field.IsValid()
} else if reply.Kind() == reflect.Ptr && reply.Elem().Kind() == reflect.Struct {
field := reply.Elem().FieldByName(fieldName)
return field, field.IsValid()
}
return reflect.Value{}, false
} | [
"func",
"findFieldOfValue",
"(",
"reply",
"reflect",
".",
"Value",
",",
"fieldName",
"string",
")",
"(",
"reflect",
".",
"Value",
",",
"bool",
")",
"{",
"if",
"reply",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Struct",
"{",
"field",
":=",
"reply",
... | // findFieldOfValue finds the field specified by its name in provided message defined as reflect.Value data type. | [
"findFieldOfValue",
"finds",
"the",
"field",
"specified",
"by",
"its",
"name",
"in",
"provided",
"message",
"defined",
"as",
"reflect",
".",
"Value",
"data",
"type",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/binapi/binapi_reflect.go#L40-L49 |
12,613 | FDio/govpp | adapter/mock/binapi/binapi_reflect.go | HasSwIfIdx | func HasSwIfIdx(msg reflect.Type) bool {
_, found := findFieldOfType(msg, swIfIndexName)
return found
} | go | func HasSwIfIdx(msg reflect.Type) bool {
_, found := findFieldOfType(msg, swIfIndexName)
return found
} | [
"func",
"HasSwIfIdx",
"(",
"msg",
"reflect",
".",
"Type",
")",
"bool",
"{",
"_",
",",
"found",
":=",
"findFieldOfType",
"(",
"msg",
",",
"swIfIndexName",
")",
"\n",
"return",
"found",
"\n",
"}"
] | // HasSwIfIdx checks whether provided message has the swIfIndex field. | [
"HasSwIfIdx",
"checks",
"whether",
"provided",
"message",
"has",
"the",
"swIfIndex",
"field",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/binapi/binapi_reflect.go#L52-L55 |
12,614 | FDio/govpp | adapter/mock/binapi/binapi_reflect.go | SetSwIfIdx | func SetSwIfIdx(msg reflect.Value, swIfIndex uint32) {
if field, found := findFieldOfValue(msg, swIfIndexName); found {
field.Set(reflect.ValueOf(swIfIndex))
}
} | go | func SetSwIfIdx(msg reflect.Value, swIfIndex uint32) {
if field, found := findFieldOfValue(msg, swIfIndexName); found {
field.Set(reflect.ValueOf(swIfIndex))
}
} | [
"func",
"SetSwIfIdx",
"(",
"msg",
"reflect",
".",
"Value",
",",
"swIfIndex",
"uint32",
")",
"{",
"if",
"field",
",",
"found",
":=",
"findFieldOfValue",
"(",
"msg",
",",
"swIfIndexName",
")",
";",
"found",
"{",
"field",
".",
"Set",
"(",
"reflect",
".",
... | // SetSwIfIdx sets the swIfIndex field of provided message to provided value. | [
"SetSwIfIdx",
"sets",
"the",
"swIfIndex",
"field",
"of",
"provided",
"message",
"to",
"provided",
"value",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/binapi/binapi_reflect.go#L58-L62 |
12,615 | FDio/govpp | adapter/mock/binapi/binapi_reflect.go | SetRetval | func SetRetval(msg reflect.Value, retVal int32) {
if field, found := findFieldOfValue(msg, retvalName); found {
field.Set(reflect.ValueOf(retVal))
}
} | go | func SetRetval(msg reflect.Value, retVal int32) {
if field, found := findFieldOfValue(msg, retvalName); found {
field.Set(reflect.ValueOf(retVal))
}
} | [
"func",
"SetRetval",
"(",
"msg",
"reflect",
".",
"Value",
",",
"retVal",
"int32",
")",
"{",
"if",
"field",
",",
"found",
":=",
"findFieldOfValue",
"(",
"msg",
",",
"retvalName",
")",
";",
"found",
"{",
"field",
".",
"Set",
"(",
"reflect",
".",
"ValueOf... | // SetRetval sets the retval field of provided message to provided value. | [
"SetRetval",
"sets",
"the",
"retval",
"field",
"of",
"provided",
"message",
"to",
"provided",
"value",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/binapi/binapi_reflect.go#L65-L69 |
12,616 | FDio/govpp | cmd/binapi-generator/generate.go | getContext | func getContext(inputFile, outputDir string) (*context, error) {
if !strings.HasSuffix(inputFile, inputFileExt) {
return nil, fmt.Errorf("invalid input file name: %q", inputFile)
}
ctx := &context{
inputFile: inputFile,
}
// package name
inputFileName := filepath.Base(inputFile)
ctx.moduleName = inputFileName[:strings.Index(inputFileName, ".")]
// alter package names for modules that are reserved keywords in Go
switch ctx.moduleName {
case "interface":
ctx.packageName = "interfaces"
case "map":
ctx.packageName = "maps"
default:
ctx.packageName = ctx.moduleName
}
// output file
packageDir := filepath.Join(outputDir, ctx.packageName)
outputFileName := ctx.packageName + outputFileExt
ctx.outputFile = filepath.Join(packageDir, outputFileName)
return ctx, nil
} | go | func getContext(inputFile, outputDir string) (*context, error) {
if !strings.HasSuffix(inputFile, inputFileExt) {
return nil, fmt.Errorf("invalid input file name: %q", inputFile)
}
ctx := &context{
inputFile: inputFile,
}
// package name
inputFileName := filepath.Base(inputFile)
ctx.moduleName = inputFileName[:strings.Index(inputFileName, ".")]
// alter package names for modules that are reserved keywords in Go
switch ctx.moduleName {
case "interface":
ctx.packageName = "interfaces"
case "map":
ctx.packageName = "maps"
default:
ctx.packageName = ctx.moduleName
}
// output file
packageDir := filepath.Join(outputDir, ctx.packageName)
outputFileName := ctx.packageName + outputFileExt
ctx.outputFile = filepath.Join(packageDir, outputFileName)
return ctx, nil
} | [
"func",
"getContext",
"(",
"inputFile",
",",
"outputDir",
"string",
")",
"(",
"*",
"context",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"inputFile",
",",
"inputFileExt",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"... | // getContext returns context details of the code generation task | [
"getContext",
"returns",
"context",
"details",
"of",
"the",
"code",
"generation",
"task"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L52-L81 |
12,617 | FDio/govpp | cmd/binapi-generator/generate.go | generatePackage | func generatePackage(ctx *context, w *bufio.Writer) error {
logf("generating package %q", ctx.packageName)
// generate file header
generateHeader(ctx, w)
generateImports(ctx, w)
if ctx.includeAPIVersionCrc {
fmt.Fprintf(w, "// %s defines API version CRC of the VPP binary API module.\n", constAPIVersionCrc)
fmt.Fprintf(w, "const %s = %v\n", constAPIVersionCrc, ctx.packageData.APIVersion)
fmt.Fprintln(w)
}
// generate services
if len(ctx.packageData.Services) > 0 {
generateServices(ctx, w, ctx.packageData.Services)
// TODO: generate implementation for Services interface
}
// generate enums
if len(ctx.packageData.Enums) > 0 {
fmt.Fprintf(w, "/* Enums */\n\n")
for _, enum := range ctx.packageData.Enums {
generateEnum(ctx, w, &enum)
}
}
// generate aliases
if len(ctx.packageData.Aliases) > 0 {
fmt.Fprintf(w, "/* Aliases */\n\n")
for _, alias := range ctx.packageData.Aliases {
generateAlias(ctx, w, &alias)
}
}
// generate types
if len(ctx.packageData.Types) > 0 {
fmt.Fprintf(w, "/* Types */\n\n")
for _, typ := range ctx.packageData.Types {
generateType(ctx, w, &typ)
}
}
// generate unions
if len(ctx.packageData.Unions) > 0 {
fmt.Fprintf(w, "/* Unions */\n\n")
for _, union := range ctx.packageData.Unions {
generateUnion(ctx, w, &union)
}
}
// generate messages
if len(ctx.packageData.Messages) > 0 {
fmt.Fprintf(w, "/* Messages */\n\n")
for _, msg := range ctx.packageData.Messages {
generateMessage(ctx, w, &msg)
}
// generate message registrations
fmt.Fprintln(w, "func init() {")
for _, msg := range ctx.packageData.Messages {
name := camelCaseName(msg.Name)
fmt.Fprintf(w, "\tapi.RegisterMessage((*%s)(nil), \"%s\")\n", name, ctx.moduleName+"."+name)
}
fmt.Fprintln(w, "}")
fmt.Fprintln(w)
fmt.Fprintln(w, "var Messages = []api.Message{")
for _, msg := range ctx.packageData.Messages {
name := camelCaseName(msg.Name)
fmt.Fprintf(w, "\t(*%s)(nil),\n", name)
}
fmt.Fprintln(w, "}")
}
// flush the data:
if err := w.Flush(); err != nil {
return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
}
return nil
} | go | func generatePackage(ctx *context, w *bufio.Writer) error {
logf("generating package %q", ctx.packageName)
// generate file header
generateHeader(ctx, w)
generateImports(ctx, w)
if ctx.includeAPIVersionCrc {
fmt.Fprintf(w, "// %s defines API version CRC of the VPP binary API module.\n", constAPIVersionCrc)
fmt.Fprintf(w, "const %s = %v\n", constAPIVersionCrc, ctx.packageData.APIVersion)
fmt.Fprintln(w)
}
// generate services
if len(ctx.packageData.Services) > 0 {
generateServices(ctx, w, ctx.packageData.Services)
// TODO: generate implementation for Services interface
}
// generate enums
if len(ctx.packageData.Enums) > 0 {
fmt.Fprintf(w, "/* Enums */\n\n")
for _, enum := range ctx.packageData.Enums {
generateEnum(ctx, w, &enum)
}
}
// generate aliases
if len(ctx.packageData.Aliases) > 0 {
fmt.Fprintf(w, "/* Aliases */\n\n")
for _, alias := range ctx.packageData.Aliases {
generateAlias(ctx, w, &alias)
}
}
// generate types
if len(ctx.packageData.Types) > 0 {
fmt.Fprintf(w, "/* Types */\n\n")
for _, typ := range ctx.packageData.Types {
generateType(ctx, w, &typ)
}
}
// generate unions
if len(ctx.packageData.Unions) > 0 {
fmt.Fprintf(w, "/* Unions */\n\n")
for _, union := range ctx.packageData.Unions {
generateUnion(ctx, w, &union)
}
}
// generate messages
if len(ctx.packageData.Messages) > 0 {
fmt.Fprintf(w, "/* Messages */\n\n")
for _, msg := range ctx.packageData.Messages {
generateMessage(ctx, w, &msg)
}
// generate message registrations
fmt.Fprintln(w, "func init() {")
for _, msg := range ctx.packageData.Messages {
name := camelCaseName(msg.Name)
fmt.Fprintf(w, "\tapi.RegisterMessage((*%s)(nil), \"%s\")\n", name, ctx.moduleName+"."+name)
}
fmt.Fprintln(w, "}")
fmt.Fprintln(w)
fmt.Fprintln(w, "var Messages = []api.Message{")
for _, msg := range ctx.packageData.Messages {
name := camelCaseName(msg.Name)
fmt.Fprintf(w, "\t(*%s)(nil),\n", name)
}
fmt.Fprintln(w, "}")
}
// flush the data:
if err := w.Flush(); err != nil {
return fmt.Errorf("flushing data to %s failed: %v", ctx.outputFile, err)
}
return nil
} | [
"func",
"generatePackage",
"(",
"ctx",
"*",
"context",
",",
"w",
"*",
"bufio",
".",
"Writer",
")",
"error",
"{",
"logf",
"(",
"\"",
"\"",
",",
"ctx",
".",
"packageName",
")",
"\n\n",
"// generate file header",
"generateHeader",
"(",
"ctx",
",",
"w",
")",... | // generatePackage generates code for the parsed package data and writes it into w | [
"generatePackage",
"generates",
"code",
"for",
"the",
"parsed",
"package",
"data",
"and",
"writes",
"it",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L84-L171 |
12,618 | FDio/govpp | cmd/binapi-generator/generate.go | generateHeader | func generateHeader(ctx *context, w io.Writer) {
fmt.Fprintln(w, "// Code generated by GoVPP binapi-generator. DO NOT EDIT.")
fmt.Fprintf(w, "// source: %s\n", ctx.inputFile)
fmt.Fprintln(w)
fmt.Fprintln(w, "/*")
fmt.Fprintf(w, " Package %s is a generated from VPP binary API module '%s'.\n", ctx.packageName, ctx.moduleName)
fmt.Fprintln(w)
fmt.Fprintln(w, " It contains following objects:")
var printObjNum = func(obj string, num int) {
if num > 0 {
if num > 1 {
if strings.HasSuffix(obj, "s") {
obj += "es"
} else {
obj += "s"
}
}
fmt.Fprintf(w, "\t%3d %s\n", num, obj)
}
}
printObjNum("service", len(ctx.packageData.Services))
printObjNum("enum", len(ctx.packageData.Enums))
printObjNum("alias", len(ctx.packageData.Aliases))
printObjNum("type", len(ctx.packageData.Types))
printObjNum("union", len(ctx.packageData.Unions))
printObjNum("message", len(ctx.packageData.Messages))
fmt.Fprintln(w, "*/")
fmt.Fprintf(w, "package %s\n", ctx.packageName)
fmt.Fprintln(w)
} | go | func generateHeader(ctx *context, w io.Writer) {
fmt.Fprintln(w, "// Code generated by GoVPP binapi-generator. DO NOT EDIT.")
fmt.Fprintf(w, "// source: %s\n", ctx.inputFile)
fmt.Fprintln(w)
fmt.Fprintln(w, "/*")
fmt.Fprintf(w, " Package %s is a generated from VPP binary API module '%s'.\n", ctx.packageName, ctx.moduleName)
fmt.Fprintln(w)
fmt.Fprintln(w, " It contains following objects:")
var printObjNum = func(obj string, num int) {
if num > 0 {
if num > 1 {
if strings.HasSuffix(obj, "s") {
obj += "es"
} else {
obj += "s"
}
}
fmt.Fprintf(w, "\t%3d %s\n", num, obj)
}
}
printObjNum("service", len(ctx.packageData.Services))
printObjNum("enum", len(ctx.packageData.Enums))
printObjNum("alias", len(ctx.packageData.Aliases))
printObjNum("type", len(ctx.packageData.Types))
printObjNum("union", len(ctx.packageData.Unions))
printObjNum("message", len(ctx.packageData.Messages))
fmt.Fprintln(w, "*/")
fmt.Fprintf(w, "package %s\n", ctx.packageName)
fmt.Fprintln(w)
} | [
"func",
"generateHeader",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
")",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\n",
"\"",
",",
"ctx",
".",
"inputFile",
... | // generateHeader writes generated package header into w | [
"generateHeader",
"writes",
"generated",
"package",
"header",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L174-L205 |
12,619 | FDio/govpp | cmd/binapi-generator/generate.go | generateImports | func generateImports(ctx *context, w io.Writer) {
fmt.Fprintf(w, "import api \"%s\"\n", govppApiImportPath)
fmt.Fprintf(w, "import struc \"%s\"\n", "github.com/lunixbochs/struc")
fmt.Fprintf(w, "import bytes \"%s\"\n", "bytes")
fmt.Fprintln(w)
fmt.Fprintf(w, "// Reference imports to suppress errors if they are not otherwise used.\n")
fmt.Fprintf(w, "var _ = api.RegisterMessage\n")
fmt.Fprintf(w, "var _ = struc.Pack\n")
fmt.Fprintf(w, "var _ = bytes.NewBuffer\n")
fmt.Fprintln(w)
/*fmt.Fprintln(w, "// This is a compile-time assertion to ensure that this generated file")
fmt.Fprintln(w, "// is compatible with the GoVPP api package it is being compiled against.")
fmt.Fprintln(w, "// A compilation error at this line likely means your copy of the")
fmt.Fprintln(w, "// GoVPP api package needs to be updated.")
fmt.Fprintln(w, "const _ = api.GoVppAPIPackageIsVersion1 // please upgrade the GoVPP api package")
fmt.Fprintln(w)*/
} | go | func generateImports(ctx *context, w io.Writer) {
fmt.Fprintf(w, "import api \"%s\"\n", govppApiImportPath)
fmt.Fprintf(w, "import struc \"%s\"\n", "github.com/lunixbochs/struc")
fmt.Fprintf(w, "import bytes \"%s\"\n", "bytes")
fmt.Fprintln(w)
fmt.Fprintf(w, "// Reference imports to suppress errors if they are not otherwise used.\n")
fmt.Fprintf(w, "var _ = api.RegisterMessage\n")
fmt.Fprintf(w, "var _ = struc.Pack\n")
fmt.Fprintf(w, "var _ = bytes.NewBuffer\n")
fmt.Fprintln(w)
/*fmt.Fprintln(w, "// This is a compile-time assertion to ensure that this generated file")
fmt.Fprintln(w, "// is compatible with the GoVPP api package it is being compiled against.")
fmt.Fprintln(w, "// A compilation error at this line likely means your copy of the")
fmt.Fprintln(w, "// GoVPP api package needs to be updated.")
fmt.Fprintln(w, "const _ = api.GoVppAPIPackageIsVersion1 // please upgrade the GoVPP api package")
fmt.Fprintln(w)*/
} | [
"func",
"generateImports",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\\\"",
"\\\"",
"\\n",
"\"",
",",
"govppApiImportPath",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"... | // generateImports writes generated package imports into w | [
"generateImports",
"writes",
"generated",
"package",
"imports",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L208-L226 |
12,620 | FDio/govpp | cmd/binapi-generator/generate.go | generateComment | func generateComment(ctx *context, w io.Writer, goName string, vppName string, objKind string) {
if objKind == "service" {
fmt.Fprintf(w, "// %s represents VPP binary API services:\n", goName)
} else {
fmt.Fprintf(w, "// %s represents VPP binary API %s '%s':\n", goName, objKind, vppName)
}
if !ctx.includeComments {
return
}
var isNotSpace = func(r rune) bool {
return !unicode.IsSpace(r)
}
// print out the source of the generated object
mapType := false
objFound := false
objTitle := fmt.Sprintf(`"%s",`, vppName)
switch objKind {
case "alias", "service":
objTitle = fmt.Sprintf(`"%s": {`, vppName)
mapType = true
}
inputBuff := bytes.NewBuffer(ctx.inputData)
inputLine := 0
var trimIndent string
var indent int
for {
line, err := inputBuff.ReadString('\n')
if err != nil {
break
}
inputLine++
noSpaceAt := strings.IndexFunc(line, isNotSpace)
if !objFound {
indent = strings.Index(line, objTitle)
if indent == -1 {
continue
}
trimIndent = line[:indent]
// If no other non-whitespace character then we are at the message header.
if trimmed := strings.TrimSpace(line); trimmed == objTitle {
objFound = true
fmt.Fprintln(w, "//")
}
} else if noSpaceAt < indent {
break // end of the definition in JSON for array types
} else if objFound && mapType && noSpaceAt <= indent {
fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
break // end of the definition in JSON for map types (aliases, services)
}
fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
}
fmt.Fprintln(w, "//")
} | go | func generateComment(ctx *context, w io.Writer, goName string, vppName string, objKind string) {
if objKind == "service" {
fmt.Fprintf(w, "// %s represents VPP binary API services:\n", goName)
} else {
fmt.Fprintf(w, "// %s represents VPP binary API %s '%s':\n", goName, objKind, vppName)
}
if !ctx.includeComments {
return
}
var isNotSpace = func(r rune) bool {
return !unicode.IsSpace(r)
}
// print out the source of the generated object
mapType := false
objFound := false
objTitle := fmt.Sprintf(`"%s",`, vppName)
switch objKind {
case "alias", "service":
objTitle = fmt.Sprintf(`"%s": {`, vppName)
mapType = true
}
inputBuff := bytes.NewBuffer(ctx.inputData)
inputLine := 0
var trimIndent string
var indent int
for {
line, err := inputBuff.ReadString('\n')
if err != nil {
break
}
inputLine++
noSpaceAt := strings.IndexFunc(line, isNotSpace)
if !objFound {
indent = strings.Index(line, objTitle)
if indent == -1 {
continue
}
trimIndent = line[:indent]
// If no other non-whitespace character then we are at the message header.
if trimmed := strings.TrimSpace(line); trimmed == objTitle {
objFound = true
fmt.Fprintln(w, "//")
}
} else if noSpaceAt < indent {
break // end of the definition in JSON for array types
} else if objFound && mapType && noSpaceAt <= indent {
fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
break // end of the definition in JSON for map types (aliases, services)
}
fmt.Fprintf(w, "//\t%s", strings.TrimPrefix(line, trimIndent))
}
fmt.Fprintln(w, "//")
} | [
"func",
"generateComment",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"goName",
"string",
",",
"vppName",
"string",
",",
"objKind",
"string",
")",
"{",
"if",
"objKind",
"==",
"\"",
"\"",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",... | // generateComment writes generated comment for the object into w | [
"generateComment",
"writes",
"generated",
"comment",
"for",
"the",
"object",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L229-L288 |
12,621 | FDio/govpp | cmd/binapi-generator/generate.go | generateServices | func generateServices(ctx *context, w *bufio.Writer, services []Service) {
// generate services comment
generateComment(ctx, w, "Services", "services", "service")
// generate interface
fmt.Fprintf(w, "type %s interface {\n", "Services")
for _, svc := range services {
generateService(ctx, w, &svc)
}
fmt.Fprintln(w, "}")
fmt.Fprintln(w)
} | go | func generateServices(ctx *context, w *bufio.Writer, services []Service) {
// generate services comment
generateComment(ctx, w, "Services", "services", "service")
// generate interface
fmt.Fprintf(w, "type %s interface {\n", "Services")
for _, svc := range services {
generateService(ctx, w, &svc)
}
fmt.Fprintln(w, "}")
fmt.Fprintln(w)
} | [
"func",
"generateServices",
"(",
"ctx",
"*",
"context",
",",
"w",
"*",
"bufio",
".",
"Writer",
",",
"services",
"[",
"]",
"Service",
")",
"{",
"// generate services comment",
"generateComment",
"(",
"ctx",
",",
"w",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",... | // generateServices writes generated code for the Services interface into w | [
"generateServices",
"writes",
"generated",
"code",
"for",
"the",
"Services",
"interface",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L291-L303 |
12,622 | FDio/govpp | cmd/binapi-generator/generate.go | generateService | func generateService(ctx *context, w io.Writer, svc *Service) {
reqTyp := camelCaseName(svc.RequestType)
// method name is same as parameter type name by default
method := reqTyp
if svc.Stream {
// use Dump as prefix instead of suffix for stream services
if m := strings.TrimSuffix(method, "Dump"); method != m {
method = "Dump" + m
}
}
params := fmt.Sprintf("*%s", reqTyp)
returns := "error"
if replyType := camelCaseName(svc.ReplyType); replyType != "" {
repTyp := fmt.Sprintf("*%s", replyType)
if svc.Stream {
repTyp = fmt.Sprintf("[]%s", repTyp)
}
returns = fmt.Sprintf("(%s, error)", repTyp)
}
fmt.Fprintf(w, "\t%s(%s) %s\n", method, params, returns)
} | go | func generateService(ctx *context, w io.Writer, svc *Service) {
reqTyp := camelCaseName(svc.RequestType)
// method name is same as parameter type name by default
method := reqTyp
if svc.Stream {
// use Dump as prefix instead of suffix for stream services
if m := strings.TrimSuffix(method, "Dump"); method != m {
method = "Dump" + m
}
}
params := fmt.Sprintf("*%s", reqTyp)
returns := "error"
if replyType := camelCaseName(svc.ReplyType); replyType != "" {
repTyp := fmt.Sprintf("*%s", replyType)
if svc.Stream {
repTyp = fmt.Sprintf("[]%s", repTyp)
}
returns = fmt.Sprintf("(%s, error)", repTyp)
}
fmt.Fprintf(w, "\t%s(%s) %s\n", method, params, returns)
} | [
"func",
"generateService",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"svc",
"*",
"Service",
")",
"{",
"reqTyp",
":=",
"camelCaseName",
"(",
"svc",
".",
"RequestType",
")",
"\n\n",
"// method name is same as parameter type name by default",
... | // generateService writes generated code for the service into w | [
"generateService",
"writes",
"generated",
"code",
"for",
"the",
"service",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L306-L329 |
12,623 | FDio/govpp | cmd/binapi-generator/generate.go | generateEnum | func generateEnum(ctx *context, w io.Writer, enum *Enum) {
name := camelCaseName(enum.Name)
typ := binapiTypes[enum.Type]
logf(" writing enum %q (%s) with %d entries", enum.Name, name, len(enum.Entries))
// generate enum comment
generateComment(ctx, w, name, enum.Name, "enum")
// generate enum definition
fmt.Fprintf(w, "type %s %s\n", name, typ)
fmt.Fprintln(w)
fmt.Fprintln(w, "const (")
// generate enum entries
for _, entry := range enum.Entries {
fmt.Fprintf(w, "\t%s %s = %v\n", entry.Name, name, entry.Value)
}
fmt.Fprintln(w, ")")
fmt.Fprintln(w)
} | go | func generateEnum(ctx *context, w io.Writer, enum *Enum) {
name := camelCaseName(enum.Name)
typ := binapiTypes[enum.Type]
logf(" writing enum %q (%s) with %d entries", enum.Name, name, len(enum.Entries))
// generate enum comment
generateComment(ctx, w, name, enum.Name, "enum")
// generate enum definition
fmt.Fprintf(w, "type %s %s\n", name, typ)
fmt.Fprintln(w)
fmt.Fprintln(w, "const (")
// generate enum entries
for _, entry := range enum.Entries {
fmt.Fprintf(w, "\t%s %s = %v\n", entry.Name, name, entry.Value)
}
fmt.Fprintln(w, ")")
fmt.Fprintln(w)
} | [
"func",
"generateEnum",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"enum",
"*",
"Enum",
")",
"{",
"name",
":=",
"camelCaseName",
"(",
"enum",
".",
"Name",
")",
"\n",
"typ",
":=",
"binapiTypes",
"[",
"enum",
".",
"Type",
"]",
"\... | // generateEnum writes generated code for the enum into w | [
"generateEnum",
"writes",
"generated",
"code",
"for",
"the",
"enum",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L332-L355 |
12,624 | FDio/govpp | cmd/binapi-generator/generate.go | generateAlias | func generateAlias(ctx *context, w io.Writer, alias *Alias) {
name := camelCaseName(alias.Name)
logf(" writing type %q (%s), length: %d", alias.Name, name, alias.Length)
// generate struct comment
generateComment(ctx, w, name, alias.Name, "alias")
// generate struct definition
fmt.Fprintf(w, "type %s ", name)
if alias.Length > 0 {
fmt.Fprintf(w, "[%d]", alias.Length)
}
dataType := convertToGoType(ctx, alias.Type)
fmt.Fprintf(w, "%s\n", dataType)
fmt.Fprintln(w)
} | go | func generateAlias(ctx *context, w io.Writer, alias *Alias) {
name := camelCaseName(alias.Name)
logf(" writing type %q (%s), length: %d", alias.Name, name, alias.Length)
// generate struct comment
generateComment(ctx, w, name, alias.Name, "alias")
// generate struct definition
fmt.Fprintf(w, "type %s ", name)
if alias.Length > 0 {
fmt.Fprintf(w, "[%d]", alias.Length)
}
dataType := convertToGoType(ctx, alias.Type)
fmt.Fprintf(w, "%s\n", dataType)
fmt.Fprintln(w)
} | [
"func",
"generateAlias",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"alias",
"*",
"Alias",
")",
"{",
"name",
":=",
"camelCaseName",
"(",
"alias",
".",
"Name",
")",
"\n\n",
"logf",
"(",
"\"",
"\"",
",",
"alias",
".",
"Name",
","... | // generateAlias writes generated code for the alias into w | [
"generateAlias",
"writes",
"generated",
"code",
"for",
"the",
"alias",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L358-L377 |
12,625 | FDio/govpp | cmd/binapi-generator/generate.go | generateUnion | func generateUnion(ctx *context, w io.Writer, union *Union) {
name := camelCaseName(union.Name)
logf(" writing union %q (%s) with %d fields", union.Name, name, len(union.Fields))
// generate struct comment
generateComment(ctx, w, name, union.Name, "union")
// generate struct definition
fmt.Fprintln(w, "type", name, "struct {")
// maximum size for union
maxSize := getUnionSize(ctx, union)
// generate data field
fieldName := "Union_data"
fmt.Fprintf(w, "\t%s [%d]byte\n", fieldName, maxSize)
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateTypeNameGetter(w, name, union.Name)
// generate CRC getter
generateCrcGetter(w, name, union.CRC)
// generate getters for fields
for _, field := range union.Fields {
fieldName := camelCaseName(field.Name)
fieldType := convertToGoType(ctx, field.Type)
generateUnionGetterSetter(w, name, fieldName, fieldType)
}
// generate union methods
//generateUnionMethods(w, name)
fmt.Fprintln(w)
} | go | func generateUnion(ctx *context, w io.Writer, union *Union) {
name := camelCaseName(union.Name)
logf(" writing union %q (%s) with %d fields", union.Name, name, len(union.Fields))
// generate struct comment
generateComment(ctx, w, name, union.Name, "union")
// generate struct definition
fmt.Fprintln(w, "type", name, "struct {")
// maximum size for union
maxSize := getUnionSize(ctx, union)
// generate data field
fieldName := "Union_data"
fmt.Fprintf(w, "\t%s [%d]byte\n", fieldName, maxSize)
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateTypeNameGetter(w, name, union.Name)
// generate CRC getter
generateCrcGetter(w, name, union.CRC)
// generate getters for fields
for _, field := range union.Fields {
fieldName := camelCaseName(field.Name)
fieldType := convertToGoType(ctx, field.Type)
generateUnionGetterSetter(w, name, fieldName, fieldType)
}
// generate union methods
//generateUnionMethods(w, name)
fmt.Fprintln(w)
} | [
"func",
"generateUnion",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"union",
"*",
"Union",
")",
"{",
"name",
":=",
"camelCaseName",
"(",
"union",
".",
"Name",
")",
"\n\n",
"logf",
"(",
"\"",
"\"",
",",
"union",
".",
"Name",
","... | // generateUnion writes generated code for the union into w | [
"generateUnion",
"writes",
"generated",
"code",
"for",
"the",
"union",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L380-L418 |
12,626 | FDio/govpp | cmd/binapi-generator/generate.go | generateType | func generateType(ctx *context, w io.Writer, typ *Type) {
name := camelCaseName(typ.Name)
logf(" writing type %q (%s) with %d fields", typ.Name, name, len(typ.Fields))
// generate struct comment
generateComment(ctx, w, name, typ.Name, "type")
// generate struct definition
fmt.Fprintf(w, "type %s struct {\n", name)
// generate struct fields
for i, field := range typ.Fields {
// skip internal fields
switch strings.ToLower(field.Name) {
case crcField, msgIdField:
continue
}
generateField(ctx, w, typ.Fields, i)
}
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateTypeNameGetter(w, name, typ.Name)
// generate CRC getter
generateCrcGetter(w, name, typ.CRC)
fmt.Fprintln(w)
} | go | func generateType(ctx *context, w io.Writer, typ *Type) {
name := camelCaseName(typ.Name)
logf(" writing type %q (%s) with %d fields", typ.Name, name, len(typ.Fields))
// generate struct comment
generateComment(ctx, w, name, typ.Name, "type")
// generate struct definition
fmt.Fprintf(w, "type %s struct {\n", name)
// generate struct fields
for i, field := range typ.Fields {
// skip internal fields
switch strings.ToLower(field.Name) {
case crcField, msgIdField:
continue
}
generateField(ctx, w, typ.Fields, i)
}
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateTypeNameGetter(w, name, typ.Name)
// generate CRC getter
generateCrcGetter(w, name, typ.CRC)
fmt.Fprintln(w)
} | [
"func",
"generateType",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"typ",
"*",
"Type",
")",
"{",
"name",
":=",
"camelCaseName",
"(",
"typ",
".",
"Name",
")",
"\n\n",
"logf",
"(",
"\"",
"\"",
",",
"typ",
".",
"Name",
",",
"nam... | // generateType writes generated code for the type into w | [
"generateType",
"writes",
"generated",
"code",
"for",
"the",
"type",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L468-L500 |
12,627 | FDio/govpp | cmd/binapi-generator/generate.go | generateMessage | func generateMessage(ctx *context, w io.Writer, msg *Message) {
name := camelCaseName(msg.Name)
logf(" writing message %q (%s) with %d fields", msg.Name, name, len(msg.Fields))
// generate struct comment
generateComment(ctx, w, name, msg.Name, "message")
// generate struct definition
fmt.Fprintf(w, "type %s struct {", name)
msgType := otherMessage
wasClientIndex := false
// generate struct fields
n := 0
for i, field := range msg.Fields {
if i == 1 {
if field.Name == clientIndexField {
// "client_index" as the second member,
// this might be an event message or a request
msgType = eventMessage
wasClientIndex = true
} else if field.Name == contextField {
// reply needs "context" as the second member
msgType = replyMessage
}
} else if i == 2 {
if wasClientIndex && field.Name == contextField {
// request needs "client_index" as the second member
// and "context" as the third member
msgType = requestMessage
}
}
// skip internal fields
switch strings.ToLower(field.Name) {
case crcField, msgIdField:
continue
case clientIndexField, contextField:
if n == 0 {
continue
}
}
n++
if n == 1 {
fmt.Fprintln(w)
}
generateField(ctx, w, msg.Fields, i)
}
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateMessageNameGetter(w, name, msg.Name)
// generate CRC getter
generateCrcGetter(w, name, msg.CRC)
// generate message type getter method
generateMessageTypeGetter(w, name, msgType)
fmt.Fprintln(w)
} | go | func generateMessage(ctx *context, w io.Writer, msg *Message) {
name := camelCaseName(msg.Name)
logf(" writing message %q (%s) with %d fields", msg.Name, name, len(msg.Fields))
// generate struct comment
generateComment(ctx, w, name, msg.Name, "message")
// generate struct definition
fmt.Fprintf(w, "type %s struct {", name)
msgType := otherMessage
wasClientIndex := false
// generate struct fields
n := 0
for i, field := range msg.Fields {
if i == 1 {
if field.Name == clientIndexField {
// "client_index" as the second member,
// this might be an event message or a request
msgType = eventMessage
wasClientIndex = true
} else if field.Name == contextField {
// reply needs "context" as the second member
msgType = replyMessage
}
} else if i == 2 {
if wasClientIndex && field.Name == contextField {
// request needs "client_index" as the second member
// and "context" as the third member
msgType = requestMessage
}
}
// skip internal fields
switch strings.ToLower(field.Name) {
case crcField, msgIdField:
continue
case clientIndexField, contextField:
if n == 0 {
continue
}
}
n++
if n == 1 {
fmt.Fprintln(w)
}
generateField(ctx, w, msg.Fields, i)
}
// generate end of the struct
fmt.Fprintln(w, "}")
// generate name getter
generateMessageNameGetter(w, name, msg.Name)
// generate CRC getter
generateCrcGetter(w, name, msg.CRC)
// generate message type getter method
generateMessageTypeGetter(w, name, msgType)
fmt.Fprintln(w)
} | [
"func",
"generateMessage",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"msg",
"*",
"Message",
")",
"{",
"name",
":=",
"camelCaseName",
"(",
"msg",
".",
"Name",
")",
"\n\n",
"logf",
"(",
"\"",
"\"",
",",
"msg",
".",
"Name",
",",
... | // generateMessage writes generated code for the message into w | [
"generateMessage",
"writes",
"generated",
"code",
"for",
"the",
"message",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L503-L568 |
12,628 | FDio/govpp | cmd/binapi-generator/generate.go | generateField | func generateField(ctx *context, w io.Writer, fields []Field, i int) {
field := fields[i]
fieldName := strings.TrimPrefix(field.Name, "_")
fieldName = camelCaseName(fieldName)
// generate length field for strings
if field.Type == "string" {
fmt.Fprintf(w, "\tXXX_%sLen uint32 `struc:\"sizeof=%s\"`\n", fieldName, fieldName)
}
dataType := convertToGoType(ctx, field.Type)
fieldType := dataType
// check if it is array
if field.Length > 0 || field.SizeFrom != "" {
if dataType == "uint8" {
dataType = "byte"
}
fieldType = "[]" + dataType
}
fmt.Fprintf(w, "\t%s %s", fieldName, fieldType)
if field.Length > 0 {
// fixed size array
fmt.Fprintf(w, "\t`struc:\"[%d]%s\"`", field.Length, dataType)
} else {
for _, f := range fields {
if f.SizeFrom == field.Name {
// variable sized array
sizeOfName := camelCaseName(f.Name)
fmt.Fprintf(w, "\t`struc:\"sizeof=%s\"`", sizeOfName)
}
}
}
fmt.Fprintln(w)
} | go | func generateField(ctx *context, w io.Writer, fields []Field, i int) {
field := fields[i]
fieldName := strings.TrimPrefix(field.Name, "_")
fieldName = camelCaseName(fieldName)
// generate length field for strings
if field.Type == "string" {
fmt.Fprintf(w, "\tXXX_%sLen uint32 `struc:\"sizeof=%s\"`\n", fieldName, fieldName)
}
dataType := convertToGoType(ctx, field.Type)
fieldType := dataType
// check if it is array
if field.Length > 0 || field.SizeFrom != "" {
if dataType == "uint8" {
dataType = "byte"
}
fieldType = "[]" + dataType
}
fmt.Fprintf(w, "\t%s %s", fieldName, fieldType)
if field.Length > 0 {
// fixed size array
fmt.Fprintf(w, "\t`struc:\"[%d]%s\"`", field.Length, dataType)
} else {
for _, f := range fields {
if f.SizeFrom == field.Name {
// variable sized array
sizeOfName := camelCaseName(f.Name)
fmt.Fprintf(w, "\t`struc:\"sizeof=%s\"`", sizeOfName)
}
}
}
fmt.Fprintln(w)
} | [
"func",
"generateField",
"(",
"ctx",
"*",
"context",
",",
"w",
"io",
".",
"Writer",
",",
"fields",
"[",
"]",
"Field",
",",
"i",
"int",
")",
"{",
"field",
":=",
"fields",
"[",
"i",
"]",
"\n\n",
"fieldName",
":=",
"strings",
".",
"TrimPrefix",
"(",
"... | // generateField writes generated code for the field into w | [
"generateField",
"writes",
"generated",
"code",
"for",
"the",
"field",
"into",
"w"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L571-L608 |
12,629 | FDio/govpp | cmd/binapi-generator/generate.go | generateTypeNameGetter | func generateTypeNameGetter(w io.Writer, structName, msgName string) {
fmt.Fprintf(w, `func (*%s) GetTypeName() string {
return %q
}
`, structName, msgName)
} | go | func generateTypeNameGetter(w io.Writer, structName, msgName string) {
fmt.Fprintf(w, `func (*%s) GetTypeName() string {
return %q
}
`, structName, msgName)
} | [
"func",
"generateTypeNameGetter",
"(",
"w",
"io",
".",
"Writer",
",",
"structName",
",",
"msgName",
"string",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"`func (*%s) GetTypeName() string {\n\treturn %q\n}\n`",
",",
"structName",
",",
"msgName",
")",
"\n",
"... | // generateTypeNameGetter generates getter for original VPP type name into the provider writer | [
"generateTypeNameGetter",
"generates",
"getter",
"for",
"original",
"VPP",
"type",
"name",
"into",
"the",
"provider",
"writer"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L619-L624 |
12,630 | FDio/govpp | cmd/binapi-generator/generate.go | generateCrcGetter | func generateCrcGetter(w io.Writer, structName, crc string) {
crc = strings.TrimPrefix(crc, "0x")
fmt.Fprintf(w, `func (*%s) GetCrcString() string {
return %q
}
`, structName, crc)
} | go | func generateCrcGetter(w io.Writer, structName, crc string) {
crc = strings.TrimPrefix(crc, "0x")
fmt.Fprintf(w, `func (*%s) GetCrcString() string {
return %q
}
`, structName, crc)
} | [
"func",
"generateCrcGetter",
"(",
"w",
"io",
".",
"Writer",
",",
"structName",
",",
"crc",
"string",
")",
"{",
"crc",
"=",
"strings",
".",
"TrimPrefix",
"(",
"crc",
",",
"\"",
"\"",
")",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"`func (*%s) GetCrcSt... | // generateCrcGetter generates getter for CRC checksum of the message definition into the provider writer | [
"generateCrcGetter",
"generates",
"getter",
"for",
"CRC",
"checksum",
"of",
"the",
"message",
"definition",
"into",
"the",
"provider",
"writer"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L627-L633 |
12,631 | FDio/govpp | cmd/binapi-generator/generate.go | generateMessageTypeGetter | func generateMessageTypeGetter(w io.Writer, structName string, msgType MessageType) {
fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
if msgType == requestMessage {
fmt.Fprintln(w, "\treturn api.RequestMessage")
} else if msgType == replyMessage {
fmt.Fprintln(w, "\treturn api.ReplyMessage")
} else if msgType == eventMessage {
fmt.Fprintln(w, "\treturn api.EventMessage")
} else {
fmt.Fprintln(w, "\treturn api.OtherMessage")
}
fmt.Fprintln(w, "}")
} | go | func generateMessageTypeGetter(w io.Writer, structName string, msgType MessageType) {
fmt.Fprintln(w, "func (*"+structName+") GetMessageType() api.MessageType {")
if msgType == requestMessage {
fmt.Fprintln(w, "\treturn api.RequestMessage")
} else if msgType == replyMessage {
fmt.Fprintln(w, "\treturn api.ReplyMessage")
} else if msgType == eventMessage {
fmt.Fprintln(w, "\treturn api.EventMessage")
} else {
fmt.Fprintln(w, "\treturn api.OtherMessage")
}
fmt.Fprintln(w, "}")
} | [
"func",
"generateMessageTypeGetter",
"(",
"w",
"io",
".",
"Writer",
",",
"structName",
"string",
",",
"msgType",
"MessageType",
")",
"{",
"fmt",
".",
"Fprintln",
"(",
"w",
",",
"\"",
"\"",
"+",
"structName",
"+",
"\"",
"\"",
")",
"\n",
"if",
"msgType",
... | // generateMessageTypeGetter generates message factory for the generated message into the provider writer | [
"generateMessageTypeGetter",
"generates",
"message",
"factory",
"for",
"the",
"generated",
"message",
"into",
"the",
"provider",
"writer"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/generate.go#L636-L648 |
12,632 | FDio/govpp | extras/libmemif/examples/raw-data/raw-data.go | SendPackets | func SendPackets(memif *libmemif.Memif, queueID uint8) {
defer wg.Done()
counter := 0
for {
select {
case <-time.After(3 * time.Second):
counter++
// Prepare fake packets.
packets := []libmemif.RawPacketData{
libmemif.RawPacketData("Packet #1 in burst number " + strconv.Itoa(counter)),
libmemif.RawPacketData("Packet #2 in burst number " + strconv.Itoa(counter)),
libmemif.RawPacketData("Packet #3 in burst number " + strconv.Itoa(counter)),
}
// Send the packets. We may not be able to do it in one burst if the ring
// is (almost) full or the internal buffer cannot contain it.
sent := 0
for {
count, err := memif.TxBurst(queueID, packets[sent:])
if err != nil {
fmt.Printf("libmemif.Memif.TxBurst() error: %v\n", err)
break
} else {
fmt.Printf("libmemif.Memif.TxBurst() has sent %d packets.\n", count)
sent += int(count)
if sent == len(packets) {
break
}
}
}
case <-stopCh:
return
}
}
} | go | func SendPackets(memif *libmemif.Memif, queueID uint8) {
defer wg.Done()
counter := 0
for {
select {
case <-time.After(3 * time.Second):
counter++
// Prepare fake packets.
packets := []libmemif.RawPacketData{
libmemif.RawPacketData("Packet #1 in burst number " + strconv.Itoa(counter)),
libmemif.RawPacketData("Packet #2 in burst number " + strconv.Itoa(counter)),
libmemif.RawPacketData("Packet #3 in burst number " + strconv.Itoa(counter)),
}
// Send the packets. We may not be able to do it in one burst if the ring
// is (almost) full or the internal buffer cannot contain it.
sent := 0
for {
count, err := memif.TxBurst(queueID, packets[sent:])
if err != nil {
fmt.Printf("libmemif.Memif.TxBurst() error: %v\n", err)
break
} else {
fmt.Printf("libmemif.Memif.TxBurst() has sent %d packets.\n", count)
sent += int(count)
if sent == len(packets) {
break
}
}
}
case <-stopCh:
return
}
}
} | [
"func",
"SendPackets",
"(",
"memif",
"*",
"libmemif",
".",
"Memif",
",",
"queueID",
"uint8",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"counter",
":=",
"0",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"3"... | // SendPackets keeps sending bursts of 3 raw-data packets every 3 seconds into
// the selected queue. | [
"SendPackets",
"keeps",
"sending",
"bursts",
"of",
"3",
"raw",
"-",
"data",
"packets",
"every",
"3",
"seconds",
"into",
"the",
"selected",
"queue",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/examples/raw-data/raw-data.go#L139-L173 |
12,633 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | NewVppClientWithInputQueueSize | func NewVppClientWithInputQueueSize(shmPrefix string, inputQueueSize uint16) adapter.VppAPI {
return &vppClient{
shmPrefix: shmPrefix,
inputQueueSize: inputQueueSize,
}
} | go | func NewVppClientWithInputQueueSize(shmPrefix string, inputQueueSize uint16) adapter.VppAPI {
return &vppClient{
shmPrefix: shmPrefix,
inputQueueSize: inputQueueSize,
}
} | [
"func",
"NewVppClientWithInputQueueSize",
"(",
"shmPrefix",
"string",
",",
"inputQueueSize",
"uint16",
")",
"adapter",
".",
"VppAPI",
"{",
"return",
"&",
"vppClient",
"{",
"shmPrefix",
":",
"shmPrefix",
",",
"inputQueueSize",
":",
"inputQueueSize",
",",
"}",
"\n",... | // NewVppClientWithInputQueueSize returns a new VPP binary API client with a custom input queue size. | [
"NewVppClientWithInputQueueSize",
"returns",
"a",
"new",
"VPP",
"binary",
"API",
"client",
"with",
"a",
"custom",
"input",
"queue",
"size",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L118-L123 |
12,634 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | Connect | func (a *vppClient) Connect() error {
if globalVppClient != nil {
return fmt.Errorf("already connected to binary API, disconnect first")
}
rxQlen := C.int(a.inputQueueSize)
var rc C.int
if a.shmPrefix == "" {
rc = C.govpp_connect(nil, rxQlen)
} else {
shm := C.CString(a.shmPrefix)
rc = C.govpp_connect(shm, rxQlen)
}
if rc != 0 {
return fmt.Errorf("connecting to VPP binary API failed (rc=%v)", rc)
}
globalVppClient = a
return nil
} | go | func (a *vppClient) Connect() error {
if globalVppClient != nil {
return fmt.Errorf("already connected to binary API, disconnect first")
}
rxQlen := C.int(a.inputQueueSize)
var rc C.int
if a.shmPrefix == "" {
rc = C.govpp_connect(nil, rxQlen)
} else {
shm := C.CString(a.shmPrefix)
rc = C.govpp_connect(shm, rxQlen)
}
if rc != 0 {
return fmt.Errorf("connecting to VPP binary API failed (rc=%v)", rc)
}
globalVppClient = a
return nil
} | [
"func",
"(",
"a",
"*",
"vppClient",
")",
"Connect",
"(",
")",
"error",
"{",
"if",
"globalVppClient",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"rxQlen",
":=",
"C",
".",
"int",
"(",
"a",
".",
"input... | // Connect connects the process to VPP. | [
"Connect",
"connects",
"the",
"process",
"to",
"VPP",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L126-L145 |
12,635 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | Disconnect | func (a *vppClient) Disconnect() error {
globalVppClient = nil
rc := C.govpp_disconnect()
if rc != 0 {
return fmt.Errorf("disconnecting from VPP binary API failed (rc=%v)", rc)
}
return nil
} | go | func (a *vppClient) Disconnect() error {
globalVppClient = nil
rc := C.govpp_disconnect()
if rc != 0 {
return fmt.Errorf("disconnecting from VPP binary API failed (rc=%v)", rc)
}
return nil
} | [
"func",
"(",
"a",
"*",
"vppClient",
")",
"Disconnect",
"(",
")",
"error",
"{",
"globalVppClient",
"=",
"nil",
"\n\n",
"rc",
":=",
"C",
".",
"govpp_disconnect",
"(",
")",
"\n",
"if",
"rc",
"!=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"... | // Disconnect disconnects the process from VPP. | [
"Disconnect",
"disconnects",
"the",
"process",
"from",
"VPP",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L148-L157 |
12,636 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | GetMsgID | func (a *vppClient) GetMsgID(msgName string, msgCrc string) (uint16, error) {
nameAndCrc := C.CString(msgName + "_" + msgCrc)
defer C.free(unsafe.Pointer(nameAndCrc))
msgID := uint16(C.govpp_get_msg_index(nameAndCrc))
if msgID == ^uint16(0) {
// VPP does not know this message
return msgID, fmt.Errorf("unknown message: %v (crc: %v)", msgName, msgCrc)
}
return msgID, nil
} | go | func (a *vppClient) GetMsgID(msgName string, msgCrc string) (uint16, error) {
nameAndCrc := C.CString(msgName + "_" + msgCrc)
defer C.free(unsafe.Pointer(nameAndCrc))
msgID := uint16(C.govpp_get_msg_index(nameAndCrc))
if msgID == ^uint16(0) {
// VPP does not know this message
return msgID, fmt.Errorf("unknown message: %v (crc: %v)", msgName, msgCrc)
}
return msgID, nil
} | [
"func",
"(",
"a",
"*",
"vppClient",
")",
"GetMsgID",
"(",
"msgName",
"string",
",",
"msgCrc",
"string",
")",
"(",
"uint16",
",",
"error",
")",
"{",
"nameAndCrc",
":=",
"C",
".",
"CString",
"(",
"msgName",
"+",
"\"",
"\"",
"+",
"msgCrc",
")",
"\n",
... | // GetMsgID returns a runtime message ID for the given message name and CRC. | [
"GetMsgID",
"returns",
"a",
"runtime",
"message",
"ID",
"for",
"the",
"given",
"message",
"name",
"and",
"CRC",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L160-L171 |
12,637 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | SendMsg | func (a *vppClient) SendMsg(context uint32, data []byte) error {
rc := C.govpp_send(C.uint32_t(context), unsafe.Pointer(&data[0]), C.size_t(len(data)))
if rc != 0 {
return fmt.Errorf("unable to send the message (rc=%v)", rc)
}
return nil
} | go | func (a *vppClient) SendMsg(context uint32, data []byte) error {
rc := C.govpp_send(C.uint32_t(context), unsafe.Pointer(&data[0]), C.size_t(len(data)))
if rc != 0 {
return fmt.Errorf("unable to send the message (rc=%v)", rc)
}
return nil
} | [
"func",
"(",
"a",
"*",
"vppClient",
")",
"SendMsg",
"(",
"context",
"uint32",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"rc",
":=",
"C",
".",
"govpp_send",
"(",
"C",
".",
"uint32_t",
"(",
"context",
")",
",",
"unsafe",
".",
"Pointer",
"(",
... | // SendMsg sends a binary-encoded message to VPP. | [
"SendMsg",
"sends",
"a",
"binary",
"-",
"encoded",
"message",
"to",
"VPP",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L174-L180 |
12,638 | FDio/govpp | adapter/vppapiclient/vppapiclient.go | WaitReady | func (a *vppClient) WaitReady() error {
// join the path to the shared memory segment
var path string
if a.shmPrefix == "" {
path = filepath.Join(shmDir, vppShmFile)
} else {
path = filepath.Join(shmDir, a.shmPrefix+"-"+vppShmFile)
}
// check if file at the path already exists
if _, err := os.Stat(path); err == nil {
// file exists, we are ready
return nil
} else if !os.IsNotExist(err) {
return err
}
// file does not exist, start watching folder
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
// start watching directory
if err := watcher.Add(shmDir); err != nil {
return err
}
for {
select {
case <-time.After(MaxWaitReady):
return fmt.Errorf("waiting for shared memory segment timed out (%s)", MaxWaitReady)
case e := <-watcher.Errors:
return e
case ev := <-watcher.Events:
if ev.Name == path {
if (ev.Op & fsnotify.Create) == fsnotify.Create {
// file was created, we are ready
return nil
}
}
}
}
} | go | func (a *vppClient) WaitReady() error {
// join the path to the shared memory segment
var path string
if a.shmPrefix == "" {
path = filepath.Join(shmDir, vppShmFile)
} else {
path = filepath.Join(shmDir, a.shmPrefix+"-"+vppShmFile)
}
// check if file at the path already exists
if _, err := os.Stat(path); err == nil {
// file exists, we are ready
return nil
} else if !os.IsNotExist(err) {
return err
}
// file does not exist, start watching folder
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer watcher.Close()
// start watching directory
if err := watcher.Add(shmDir); err != nil {
return err
}
for {
select {
case <-time.After(MaxWaitReady):
return fmt.Errorf("waiting for shared memory segment timed out (%s)", MaxWaitReady)
case e := <-watcher.Errors:
return e
case ev := <-watcher.Events:
if ev.Name == path {
if (ev.Op & fsnotify.Create) == fsnotify.Create {
// file was created, we are ready
return nil
}
}
}
}
} | [
"func",
"(",
"a",
"*",
"vppClient",
")",
"WaitReady",
"(",
")",
"error",
"{",
"// join the path to the shared memory segment",
"var",
"path",
"string",
"\n",
"if",
"a",
".",
"shmPrefix",
"==",
"\"",
"\"",
"{",
"path",
"=",
"filepath",
".",
"Join",
"(",
"sh... | // WaitReady blocks until shared memory for sending
// binary api calls is present on the file system. | [
"WaitReady",
"blocks",
"until",
"shared",
"memory",
"for",
"sending",
"binary",
"api",
"calls",
"is",
"present",
"on",
"the",
"file",
"system",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/vppapiclient/vppapiclient.go#L190-L234 |
12,639 | FDio/govpp | extras/libmemif/error.go | newMemifError | func newMemifError(code int, desc ...string) *MemifError {
var err *MemifError
if len(desc) > 0 {
err = &MemifError{code: code, description: "libmemif: " + desc[0]}
} else {
err = &MemifError{code: code, description: "libmemif: " + C.GoString(C.memif_strerror(C.int(code)))}
}
errorRegistry[code] = err
return err
} | go | func newMemifError(code int, desc ...string) *MemifError {
var err *MemifError
if len(desc) > 0 {
err = &MemifError{code: code, description: "libmemif: " + desc[0]}
} else {
err = &MemifError{code: code, description: "libmemif: " + C.GoString(C.memif_strerror(C.int(code)))}
}
errorRegistry[code] = err
return err
} | [
"func",
"newMemifError",
"(",
"code",
"int",
",",
"desc",
"...",
"string",
")",
"*",
"MemifError",
"{",
"var",
"err",
"*",
"MemifError",
"\n",
"if",
"len",
"(",
"desc",
")",
">",
"0",
"{",
"err",
"=",
"&",
"MemifError",
"{",
"code",
":",
"code",
",... | // newMemifError builds and registers a new MemifError. | [
"newMemifError",
"builds",
"and",
"registers",
"a",
"new",
"MemifError",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/error.go#L102-L111 |
12,640 | FDio/govpp | extras/libmemif/error.go | getMemifError | func getMemifError(code int) error {
if code == 0 {
return nil /* success */
}
err, known := errorRegistry[code]
if !known {
return ErrUnknown
}
return err
} | go | func getMemifError(code int) error {
if code == 0 {
return nil /* success */
}
err, known := errorRegistry[code]
if !known {
return ErrUnknown
}
return err
} | [
"func",
"getMemifError",
"(",
"code",
"int",
")",
"error",
"{",
"if",
"code",
"==",
"0",
"{",
"return",
"nil",
"/* success */",
"\n",
"}",
"\n",
"err",
",",
"known",
":=",
"errorRegistry",
"[",
"code",
"]",
"\n",
"if",
"!",
"known",
"{",
"return",
"E... | // getMemifError returns the MemifError associated with the given C-libmemif
// error code. | [
"getMemifError",
"returns",
"the",
"MemifError",
"associated",
"with",
"the",
"given",
"C",
"-",
"libmemif",
"error",
"code",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/error.go#L115-L124 |
12,641 | FDio/govpp | extras/libmemif/adapter.go | Cleanup | func Cleanup() error {
context.lock.Lock()
defer context.lock.Unlock()
if !context.initialized {
return ErrNotInit
}
log.Debug("Closing libmemif library")
// Delete all active interfaces.
for _, memif := range context.memifs {
memif.Close()
}
// Stop the event loop (if supported by C-libmemif).
errCode := C.memif_cancel_poll_event()
err := getMemifError(int(errCode))
if err == nil {
log.Debug("Waiting for pollEvents() to stop...")
context.wg.Wait()
log.Debug("pollEvents() has stopped...")
} else {
log.WithField("err", err).Debug("NOT Waiting for pollEvents to stop...")
}
// Run cleanup for C-libmemif.
err = getMemifError(int(C.memif_cleanup()))
if err == nil {
context.initialized = false
log.Debug("libmemif library was closed")
}
return err
} | go | func Cleanup() error {
context.lock.Lock()
defer context.lock.Unlock()
if !context.initialized {
return ErrNotInit
}
log.Debug("Closing libmemif library")
// Delete all active interfaces.
for _, memif := range context.memifs {
memif.Close()
}
// Stop the event loop (if supported by C-libmemif).
errCode := C.memif_cancel_poll_event()
err := getMemifError(int(errCode))
if err == nil {
log.Debug("Waiting for pollEvents() to stop...")
context.wg.Wait()
log.Debug("pollEvents() has stopped...")
} else {
log.WithField("err", err).Debug("NOT Waiting for pollEvents to stop...")
}
// Run cleanup for C-libmemif.
err = getMemifError(int(C.memif_cleanup()))
if err == nil {
context.initialized = false
log.Debug("libmemif library was closed")
}
return err
} | [
"func",
"Cleanup",
"(",
")",
"error",
"{",
"context",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"context",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"!",
"context",
".",
"initialized",
"{",
"return",
"ErrNotInit",
"\n",
"}",
"\n\n"... | // Cleanup cleans up all the resources allocated by libmemif. | [
"Cleanup",
"cleans",
"up",
"all",
"the",
"resources",
"allocated",
"by",
"libmemif",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L505-L538 |
12,642 | FDio/govpp | extras/libmemif/adapter.go | SetRxMode | func (memif *Memif) SetRxMode(queueID uint8, rxMode RxMode) (err error) {
var cRxMode C.memif_rx_mode_t
switch rxMode {
case RxModeInterrupt:
cRxMode = C.MEMIF_RX_MODE_INTERRUPT
case RxModePolling:
cRxMode = C.MEMIF_RX_MODE_POLLING
default:
cRxMode = C.MEMIF_RX_MODE_INTERRUPT
}
errCode := C.memif_set_rx_mode(memif.cHandle, cRxMode, C.uint16_t(queueID))
return getMemifError(int(errCode))
} | go | func (memif *Memif) SetRxMode(queueID uint8, rxMode RxMode) (err error) {
var cRxMode C.memif_rx_mode_t
switch rxMode {
case RxModeInterrupt:
cRxMode = C.MEMIF_RX_MODE_INTERRUPT
case RxModePolling:
cRxMode = C.MEMIF_RX_MODE_POLLING
default:
cRxMode = C.MEMIF_RX_MODE_INTERRUPT
}
errCode := C.memif_set_rx_mode(memif.cHandle, cRxMode, C.uint16_t(queueID))
return getMemifError(int(errCode))
} | [
"func",
"(",
"memif",
"*",
"Memif",
")",
"SetRxMode",
"(",
"queueID",
"uint8",
",",
"rxMode",
"RxMode",
")",
"(",
"err",
"error",
")",
"{",
"var",
"cRxMode",
"C",
".",
"memif_rx_mode_t",
"\n",
"switch",
"rxMode",
"{",
"case",
"RxModeInterrupt",
":",
"cRx... | // SetRxMode allows to switch between the interrupt and the polling mode for Rx.
// The method is thread-safe. | [
"SetRxMode",
"allows",
"to",
"switch",
"between",
"the",
"interrupt",
"and",
"the",
"polling",
"mode",
"for",
"Rx",
".",
"The",
"method",
"is",
"thread",
"-",
"safe",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L680-L692 |
12,643 | FDio/govpp | extras/libmemif/adapter.go | GetDetails | func (memif *Memif) GetDetails() (details *MemifDetails, err error) {
cDetails := C.govpp_memif_details_t{}
var buf *C.char
// Get memif details from C-libmemif.
errCode := C.govpp_memif_get_details(memif.cHandle, &cDetails, &buf)
err = getMemifError(int(errCode))
if err != nil {
return nil, err
}
defer C.free(unsafe.Pointer(buf))
// Convert details from C to Go.
details = &MemifDetails{}
// - metadata:
details.IfName = C.GoString(cDetails.if_name)
details.InstanceName = C.GoString(cDetails.inst_name)
details.ConnID = uint32(cDetails.id)
details.SocketFilename = C.GoString(cDetails.socket_filename)
if cDetails.secret != nil {
details.Secret = C.GoString(cDetails.secret)
}
details.IsMaster = cDetails.role == C.uint8_t(0)
switch cDetails.mode {
case C.MEMIF_INTERFACE_MODE_ETHERNET:
details.Mode = IfModeEthernet
case C.MEMIF_INTERFACE_MODE_IP:
details.Mode = IfModeIP
case C.MEMIF_INTERFACE_MODE_PUNT_INJECT:
details.Mode = IfModePuntInject
default:
details.Mode = IfModeEthernet
}
// - connection details:
details.RemoteIfName = C.GoString(cDetails.remote_if_name)
details.RemoteInstanceName = C.GoString(cDetails.remote_inst_name)
details.HasLink = cDetails.link_up_down == C.uint8_t(1)
// - RX queues:
var i uint8
for i = 0; i < uint8(cDetails.rx_queues_num); i++ {
cRxQueue := C.govpp_get_rx_queue_details(&cDetails, C.int(i))
queueDetails := MemifQueueDetails{
QueueID: uint8(cRxQueue.qid),
RingSize: uint32(cRxQueue.ring_size),
BufferSize: uint16(cRxQueue.buffer_size),
}
details.RxQueues = append(details.RxQueues, queueDetails)
}
// - TX queues:
for i = 0; i < uint8(cDetails.tx_queues_num); i++ {
cTxQueue := C.govpp_get_tx_queue_details(&cDetails, C.int(i))
queueDetails := MemifQueueDetails{
QueueID: uint8(cTxQueue.qid),
RingSize: uint32(cTxQueue.ring_size),
BufferSize: uint16(cTxQueue.buffer_size),
}
details.TxQueues = append(details.TxQueues, queueDetails)
}
return details, nil
} | go | func (memif *Memif) GetDetails() (details *MemifDetails, err error) {
cDetails := C.govpp_memif_details_t{}
var buf *C.char
// Get memif details from C-libmemif.
errCode := C.govpp_memif_get_details(memif.cHandle, &cDetails, &buf)
err = getMemifError(int(errCode))
if err != nil {
return nil, err
}
defer C.free(unsafe.Pointer(buf))
// Convert details from C to Go.
details = &MemifDetails{}
// - metadata:
details.IfName = C.GoString(cDetails.if_name)
details.InstanceName = C.GoString(cDetails.inst_name)
details.ConnID = uint32(cDetails.id)
details.SocketFilename = C.GoString(cDetails.socket_filename)
if cDetails.secret != nil {
details.Secret = C.GoString(cDetails.secret)
}
details.IsMaster = cDetails.role == C.uint8_t(0)
switch cDetails.mode {
case C.MEMIF_INTERFACE_MODE_ETHERNET:
details.Mode = IfModeEthernet
case C.MEMIF_INTERFACE_MODE_IP:
details.Mode = IfModeIP
case C.MEMIF_INTERFACE_MODE_PUNT_INJECT:
details.Mode = IfModePuntInject
default:
details.Mode = IfModeEthernet
}
// - connection details:
details.RemoteIfName = C.GoString(cDetails.remote_if_name)
details.RemoteInstanceName = C.GoString(cDetails.remote_inst_name)
details.HasLink = cDetails.link_up_down == C.uint8_t(1)
// - RX queues:
var i uint8
for i = 0; i < uint8(cDetails.rx_queues_num); i++ {
cRxQueue := C.govpp_get_rx_queue_details(&cDetails, C.int(i))
queueDetails := MemifQueueDetails{
QueueID: uint8(cRxQueue.qid),
RingSize: uint32(cRxQueue.ring_size),
BufferSize: uint16(cRxQueue.buffer_size),
}
details.RxQueues = append(details.RxQueues, queueDetails)
}
// - TX queues:
for i = 0; i < uint8(cDetails.tx_queues_num); i++ {
cTxQueue := C.govpp_get_tx_queue_details(&cDetails, C.int(i))
queueDetails := MemifQueueDetails{
QueueID: uint8(cTxQueue.qid),
RingSize: uint32(cTxQueue.ring_size),
BufferSize: uint16(cTxQueue.buffer_size),
}
details.TxQueues = append(details.TxQueues, queueDetails)
}
return details, nil
} | [
"func",
"(",
"memif",
"*",
"Memif",
")",
"GetDetails",
"(",
")",
"(",
"details",
"*",
"MemifDetails",
",",
"err",
"error",
")",
"{",
"cDetails",
":=",
"C",
".",
"govpp_memif_details_t",
"{",
"}",
"\n",
"var",
"buf",
"*",
"C",
".",
"char",
"\n\n",
"//... | // GetDetails returns a detailed runtime information about this memif.
// The method is thread-safe. | [
"GetDetails",
"returns",
"a",
"detailed",
"runtime",
"information",
"about",
"this",
"memif",
".",
"The",
"method",
"is",
"thread",
"-",
"safe",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L696-L756 |
12,644 | FDio/govpp | extras/libmemif/adapter.go | Close | func (memif *Memif) Close() error {
log.WithField("ifName", memif.IfName).Debug("Closing the memif interface")
// Delete memif from C-libmemif.
err := getMemifError(int(C.memif_delete(&memif.cHandle)))
if err != nil {
// Close memif-global interrupt channel.
close(memif.intCh)
// Close file descriptor stopQPollFd.
C.close(C.int(memif.stopQPollFd))
}
context.lock.Lock()
defer context.lock.Unlock()
// Unregister the interface from the context.
delete(context.memifs, memif.ifIndex)
log.WithField("ifName", memif.IfName).Debug("memif interface was closed")
return err
} | go | func (memif *Memif) Close() error {
log.WithField("ifName", memif.IfName).Debug("Closing the memif interface")
// Delete memif from C-libmemif.
err := getMemifError(int(C.memif_delete(&memif.cHandle)))
if err != nil {
// Close memif-global interrupt channel.
close(memif.intCh)
// Close file descriptor stopQPollFd.
C.close(C.int(memif.stopQPollFd))
}
context.lock.Lock()
defer context.lock.Unlock()
// Unregister the interface from the context.
delete(context.memifs, memif.ifIndex)
log.WithField("ifName", memif.IfName).Debug("memif interface was closed")
return err
} | [
"func",
"(",
"memif",
"*",
"Memif",
")",
"Close",
"(",
")",
"error",
"{",
"log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"memif",
".",
"IfName",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// Delete memif from C-libmemif.",
"err",
":=",
"getMemif... | // Close removes the memif interface. If the memif is in the connected state,
// the connection is first properly closed.
// Do not access memif after it is closed, let garbage collector to remove it. | [
"Close",
"removes",
"the",
"memif",
"interface",
".",
"If",
"the",
"memif",
"is",
"in",
"the",
"connected",
"state",
"the",
"connection",
"is",
"first",
"properly",
"closed",
".",
"Do",
"not",
"access",
"memif",
"after",
"it",
"is",
"closed",
"let",
"garba... | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L1005-L1025 |
12,645 | FDio/govpp | extras/libmemif/adapter.go | pollEvents | func pollEvents() {
defer context.wg.Done()
for {
errCode := C.memif_poll_event(C.int(-1))
err := getMemifError(int(errCode))
if err == ErrPollCanceled {
return
}
}
} | go | func pollEvents() {
defer context.wg.Done()
for {
errCode := C.memif_poll_event(C.int(-1))
err := getMemifError(int(errCode))
if err == ErrPollCanceled {
return
}
}
} | [
"func",
"pollEvents",
"(",
")",
"{",
"defer",
"context",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"for",
"{",
"errCode",
":=",
"C",
".",
"memif_poll_event",
"(",
"C",
".",
"int",
"(",
"-",
"1",
")",
")",
"\n",
"err",
":=",
"getMemifError",
"(",
"i... | // pollEvents repeatedly polls for a libmemif event. | [
"pollEvents",
"repeatedly",
"polls",
"for",
"a",
"libmemif",
"event",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L1092-L1101 |
12,646 | FDio/govpp | extras/libmemif/adapter.go | pollRxQueue | func pollRxQueue(memif *Memif, queueID uint8) {
defer memif.wg.Done()
log.WithFields(logger.Fields{
"ifName": memif.IfName,
"queue-ID": queueID,
}).Debug("Started queue interrupt polling.")
var qfd C.int
errCode := C.memif_get_queue_efd(memif.cHandle, C.uint16_t(queueID), &qfd)
err := getMemifError(int(errCode))
if err != nil {
log.WithField("err", err).Error("memif_get_queue_efd() failed")
return
}
// Create epoll file descriptor.
var event [1]syscall.EpollEvent
epFd, err := syscall.EpollCreate1(0)
if err != nil {
log.WithField("err", err).Error("epoll_create1() failed")
return
}
defer syscall.Close(epFd)
// Add Rx queue interrupt file descriptor.
event[0].Events = syscall.EPOLLIN
event[0].Fd = int32(qfd)
if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, int(qfd), &event[0]); err != nil {
log.WithField("err", err).Error("epoll_ctl() failed")
return
}
// Add file descriptor used to stop this go routine.
event[0].Events = syscall.EPOLLIN
event[0].Fd = int32(memif.stopQPollFd)
if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, memif.stopQPollFd, &event[0]); err != nil {
log.WithField("err", err).Error("epoll_ctl() failed")
return
}
// Poll for interrupts.
for {
_, err := syscall.EpollWait(epFd, event[:], -1)
if err != nil {
log.WithField("err", err).Error("epoll_wait() failed")
return
}
// Handle Rx Interrupt.
if event[0].Fd == int32(qfd) {
// Consume the interrupt event.
buf := make([]byte, 8)
_, err = syscall.Read(int(qfd), buf[:])
if err != nil {
log.WithField("err", err).Warn("read() failed")
}
// Send signal to memif-global interrupt channel.
select {
case memif.intCh <- queueID:
break
default:
break
}
// Send signal to queue-specific interrupt channel.
select {
case memif.queueIntCh[queueID] <- struct{}{}:
break
default:
break
}
}
// Stop the go routine if requested.
if event[0].Fd == int32(memif.stopQPollFd) {
log.WithFields(logger.Fields{
"ifName": memif.IfName,
"queue-ID": queueID,
}).Debug("Stopped queue interrupt polling.")
return
}
}
} | go | func pollRxQueue(memif *Memif, queueID uint8) {
defer memif.wg.Done()
log.WithFields(logger.Fields{
"ifName": memif.IfName,
"queue-ID": queueID,
}).Debug("Started queue interrupt polling.")
var qfd C.int
errCode := C.memif_get_queue_efd(memif.cHandle, C.uint16_t(queueID), &qfd)
err := getMemifError(int(errCode))
if err != nil {
log.WithField("err", err).Error("memif_get_queue_efd() failed")
return
}
// Create epoll file descriptor.
var event [1]syscall.EpollEvent
epFd, err := syscall.EpollCreate1(0)
if err != nil {
log.WithField("err", err).Error("epoll_create1() failed")
return
}
defer syscall.Close(epFd)
// Add Rx queue interrupt file descriptor.
event[0].Events = syscall.EPOLLIN
event[0].Fd = int32(qfd)
if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, int(qfd), &event[0]); err != nil {
log.WithField("err", err).Error("epoll_ctl() failed")
return
}
// Add file descriptor used to stop this go routine.
event[0].Events = syscall.EPOLLIN
event[0].Fd = int32(memif.stopQPollFd)
if err = syscall.EpollCtl(epFd, syscall.EPOLL_CTL_ADD, memif.stopQPollFd, &event[0]); err != nil {
log.WithField("err", err).Error("epoll_ctl() failed")
return
}
// Poll for interrupts.
for {
_, err := syscall.EpollWait(epFd, event[:], -1)
if err != nil {
log.WithField("err", err).Error("epoll_wait() failed")
return
}
// Handle Rx Interrupt.
if event[0].Fd == int32(qfd) {
// Consume the interrupt event.
buf := make([]byte, 8)
_, err = syscall.Read(int(qfd), buf[:])
if err != nil {
log.WithField("err", err).Warn("read() failed")
}
// Send signal to memif-global interrupt channel.
select {
case memif.intCh <- queueID:
break
default:
break
}
// Send signal to queue-specific interrupt channel.
select {
case memif.queueIntCh[queueID] <- struct{}{}:
break
default:
break
}
}
// Stop the go routine if requested.
if event[0].Fd == int32(memif.stopQPollFd) {
log.WithFields(logger.Fields{
"ifName": memif.IfName,
"queue-ID": queueID,
}).Debug("Stopped queue interrupt polling.")
return
}
}
} | [
"func",
"pollRxQueue",
"(",
"memif",
"*",
"Memif",
",",
"queueID",
"uint8",
")",
"{",
"defer",
"memif",
".",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"log",
".",
"WithFields",
"(",
"logger",
".",
"Fields",
"{",
"\"",
"\"",
":",
"memif",
".",
"IfName",
... | // pollRxQueue repeatedly polls an Rx queue for interrupts. | [
"pollRxQueue",
"repeatedly",
"polls",
"an",
"Rx",
"queue",
"for",
"interrupts",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/adapter.go#L1104-L1188 |
12,647 | FDio/govpp | extras/libmemif/examples/icmp-responder/icmp-responder.go | IcmpResponder | func IcmpResponder(memif *libmemif.Memif, queueID uint8) {
defer wg.Done()
// Get channel which fires every time there are packets to read on the queue.
interruptCh, err := memif.GetQueueInterruptChan(queueID)
if err != nil {
// Example of libmemif error handling code:
switch err {
case libmemif.ErrQueueID:
fmt.Printf("libmemif.Memif.GetQueueInterruptChan() complains about invalid queue id!?")
// Here you would put all the errors that need to be handled individually...
default:
fmt.Printf("libmemif.Memif.GetQueueInterruptChan() error: %v\n", err)
}
return
}
for {
select {
case <-interruptCh:
// Read all packets from the queue but at most 10 at once.
// Since there is only one interrupt signal sent for an entire burst
// of packets, an interrupt handling routine should repeatedly call
// RxBurst() until the function returns an empty slice of packets.
// This way it is ensured that there are no packets left
// on the queue unread when the interrupt signal is cleared.
for {
packets, err := memif.RxBurst(queueID, 10)
if err != nil {
fmt.Printf("libmemif.Memif.RxBurst() error: %v\n", err)
// Skip this burst, continue with the next one 3secs later...
break
}
if len(packets) == 0 {
// No more packets to read until the next interrupt.
break
}
// Generate response for each supported request.
responses := []libmemif.RawPacketData{}
for _, packet := range packets {
fmt.Println("Received new packet:")
DumpPacket(packet)
response, err := GeneratePacketResponse(packet)
if err == nil {
fmt.Println("Sending response:")
DumpPacket(response)
responses = append(responses, response)
} else {
fmt.Printf("Failed to generate response: %v\n", err)
}
}
// Send pongs / ARP responses. We may not be able to do it in one
// burst if the ring is (almost) full or the internal buffer cannot
// contain it.
sent := 0
for {
count, err := memif.TxBurst(queueID, responses[sent:])
if err != nil {
fmt.Printf("libmemif.Memif.TxBurst() error: %v\n", err)
break
} else {
fmt.Printf("libmemif.Memif.TxBurst() has sent %d packets.\n", count)
sent += int(count)
if sent == len(responses) {
break
}
}
}
}
case <-stopCh:
return
}
}
} | go | func IcmpResponder(memif *libmemif.Memif, queueID uint8) {
defer wg.Done()
// Get channel which fires every time there are packets to read on the queue.
interruptCh, err := memif.GetQueueInterruptChan(queueID)
if err != nil {
// Example of libmemif error handling code:
switch err {
case libmemif.ErrQueueID:
fmt.Printf("libmemif.Memif.GetQueueInterruptChan() complains about invalid queue id!?")
// Here you would put all the errors that need to be handled individually...
default:
fmt.Printf("libmemif.Memif.GetQueueInterruptChan() error: %v\n", err)
}
return
}
for {
select {
case <-interruptCh:
// Read all packets from the queue but at most 10 at once.
// Since there is only one interrupt signal sent for an entire burst
// of packets, an interrupt handling routine should repeatedly call
// RxBurst() until the function returns an empty slice of packets.
// This way it is ensured that there are no packets left
// on the queue unread when the interrupt signal is cleared.
for {
packets, err := memif.RxBurst(queueID, 10)
if err != nil {
fmt.Printf("libmemif.Memif.RxBurst() error: %v\n", err)
// Skip this burst, continue with the next one 3secs later...
break
}
if len(packets) == 0 {
// No more packets to read until the next interrupt.
break
}
// Generate response for each supported request.
responses := []libmemif.RawPacketData{}
for _, packet := range packets {
fmt.Println("Received new packet:")
DumpPacket(packet)
response, err := GeneratePacketResponse(packet)
if err == nil {
fmt.Println("Sending response:")
DumpPacket(response)
responses = append(responses, response)
} else {
fmt.Printf("Failed to generate response: %v\n", err)
}
}
// Send pongs / ARP responses. We may not be able to do it in one
// burst if the ring is (almost) full or the internal buffer cannot
// contain it.
sent := 0
for {
count, err := memif.TxBurst(queueID, responses[sent:])
if err != nil {
fmt.Printf("libmemif.Memif.TxBurst() error: %v\n", err)
break
} else {
fmt.Printf("libmemif.Memif.TxBurst() has sent %d packets.\n", count)
sent += int(count)
if sent == len(responses) {
break
}
}
}
}
case <-stopCh:
return
}
}
} | [
"func",
"IcmpResponder",
"(",
"memif",
"*",
"libmemif",
".",
"Memif",
",",
"queueID",
"uint8",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"// Get channel which fires every time there are packets to read on the queue.",
"interruptCh",
",",
"err",
":=",
"... | // IcmpResponder answers to ICMP pings with ICMP pongs. | [
"IcmpResponder",
"answers",
"to",
"ICMP",
"pings",
"with",
"ICMP",
"pongs",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/examples/icmp-responder/icmp-responder.go#L120-L193 |
12,648 | FDio/govpp | extras/libmemif/examples/icmp-responder/icmp-responder.go | DumpPacket | func DumpPacket(packetData libmemif.RawPacketData) {
packet := gopacket.NewPacket(packetData, layers.LayerTypeEthernet, gopacket.Default)
fmt.Println(packet.Dump())
} | go | func DumpPacket(packetData libmemif.RawPacketData) {
packet := gopacket.NewPacket(packetData, layers.LayerTypeEthernet, gopacket.Default)
fmt.Println(packet.Dump())
} | [
"func",
"DumpPacket",
"(",
"packetData",
"libmemif",
".",
"RawPacketData",
")",
"{",
"packet",
":=",
"gopacket",
".",
"NewPacket",
"(",
"packetData",
",",
"layers",
".",
"LayerTypeEthernet",
",",
"gopacket",
".",
"Default",
")",
"\n",
"fmt",
".",
"Println",
... | // DumpPacket prints a human-readable description of the packet. | [
"DumpPacket",
"prints",
"a",
"human",
"-",
"readable",
"description",
"of",
"the",
"packet",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/examples/icmp-responder/icmp-responder.go#L196-L199 |
12,649 | FDio/govpp | core/channel.go | receiveReplyInternal | func (ch *Channel) receiveReplyInternal(msg api.Message, expSeqNum uint16) (lastReplyReceived bool, err error) {
if msg == nil {
return false, errors.New("nil message passed in")
}
var ignore bool
if vppReply := ch.delayedReply; vppReply != nil {
// try the delayed reply
ch.delayedReply = nil
ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
if !ignore {
return lastReplyReceived, err
}
}
timer := time.NewTimer(ch.replyTimeout)
for {
select {
// blocks until a reply comes to ReplyChan or until timeout expires
case vppReply := <-ch.replyChan:
ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
if ignore {
logrus.Warnf("ignoring reply: %+v", vppReply)
continue
}
return lastReplyReceived, err
case <-timer.C:
err = fmt.Errorf("no reply received within the timeout period %s", ch.replyTimeout)
return false, err
}
}
return
} | go | func (ch *Channel) receiveReplyInternal(msg api.Message, expSeqNum uint16) (lastReplyReceived bool, err error) {
if msg == nil {
return false, errors.New("nil message passed in")
}
var ignore bool
if vppReply := ch.delayedReply; vppReply != nil {
// try the delayed reply
ch.delayedReply = nil
ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
if !ignore {
return lastReplyReceived, err
}
}
timer := time.NewTimer(ch.replyTimeout)
for {
select {
// blocks until a reply comes to ReplyChan or until timeout expires
case vppReply := <-ch.replyChan:
ignore, lastReplyReceived, err = ch.processReply(vppReply, expSeqNum, msg)
if ignore {
logrus.Warnf("ignoring reply: %+v", vppReply)
continue
}
return lastReplyReceived, err
case <-timer.C:
err = fmt.Errorf("no reply received within the timeout period %s", ch.replyTimeout)
return false, err
}
}
return
} | [
"func",
"(",
"ch",
"*",
"Channel",
")",
"receiveReplyInternal",
"(",
"msg",
"api",
".",
"Message",
",",
"expSeqNum",
"uint16",
")",
"(",
"lastReplyReceived",
"bool",
",",
"err",
"error",
")",
"{",
"if",
"msg",
"==",
"nil",
"{",
"return",
"false",
",",
... | // receiveReplyInternal receives a reply from the reply channel into the provided msg structure. | [
"receiveReplyInternal",
"receives",
"a",
"reply",
"from",
"the",
"reply",
"channel",
"into",
"the",
"provided",
"msg",
"structure",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/channel.go#L235-L269 |
12,650 | FDio/govpp | adapter/mock/mock_stats_adapter.go | ListStats | func (a *StatsAdapter) ListStats(patterns ...string) ([]string, error) {
var statNames []string
for _, stat := range a.entries {
statNames = append(statNames, stat.Name)
}
return statNames, nil
} | go | func (a *StatsAdapter) ListStats(patterns ...string) ([]string, error) {
var statNames []string
for _, stat := range a.entries {
statNames = append(statNames, stat.Name)
}
return statNames, nil
} | [
"func",
"(",
"a",
"*",
"StatsAdapter",
")",
"ListStats",
"(",
"patterns",
"...",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"statNames",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"stat",
":=",
"range",
"a",
".",
"entrie... | // ListStats mocks name listing for all stats. | [
"ListStats",
"mocks",
"name",
"listing",
"for",
"all",
"stats",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_stats_adapter.go#L45-L51 |
12,651 | FDio/govpp | adapter/mock/mock_stats_adapter.go | DumpStats | func (a *StatsAdapter) DumpStats(patterns ...string) ([]*adapter.StatEntry, error) {
return a.entries, nil
} | go | func (a *StatsAdapter) DumpStats(patterns ...string) ([]*adapter.StatEntry, error) {
return a.entries, nil
} | [
"func",
"(",
"a",
"*",
"StatsAdapter",
")",
"DumpStats",
"(",
"patterns",
"...",
"string",
")",
"(",
"[",
"]",
"*",
"adapter",
".",
"StatEntry",
",",
"error",
")",
"{",
"return",
"a",
".",
"entries",
",",
"nil",
"\n",
"}"
] | // DumpStats mocks all stat entries dump. | [
"DumpStats",
"mocks",
"all",
"stat",
"entries",
"dump",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_stats_adapter.go#L54-L56 |
12,652 | FDio/govpp | cmd/binapi-generator/types.go | convertToGoType | func convertToGoType(ctx *context, binapiType string) (typ string) {
if t, ok := binapiTypes[binapiType]; ok {
// basic types
typ = t
} else if r, ok := ctx.packageData.RefMap[binapiType]; ok {
// specific types (enums/types/unions)
typ = camelCaseName(r)
} else {
switch binapiType {
case "bool", "string":
typ = binapiType
default:
// fallback type
log.Warnf("found unknown VPP binary API type %q, using byte", binapiType)
typ = "byte"
}
}
return typ
} | go | func convertToGoType(ctx *context, binapiType string) (typ string) {
if t, ok := binapiTypes[binapiType]; ok {
// basic types
typ = t
} else if r, ok := ctx.packageData.RefMap[binapiType]; ok {
// specific types (enums/types/unions)
typ = camelCaseName(r)
} else {
switch binapiType {
case "bool", "string":
typ = binapiType
default:
// fallback type
log.Warnf("found unknown VPP binary API type %q, using byte", binapiType)
typ = "byte"
}
}
return typ
} | [
"func",
"convertToGoType",
"(",
"ctx",
"*",
"context",
",",
"binapiType",
"string",
")",
"(",
"typ",
"string",
")",
"{",
"if",
"t",
",",
"ok",
":=",
"binapiTypes",
"[",
"binapiType",
"]",
";",
"ok",
"{",
"// basic types",
"typ",
"=",
"t",
"\n",
"}",
... | // convertToGoType translates the VPP binary API type into Go type | [
"convertToGoType",
"translates",
"the",
"VPP",
"binary",
"API",
"type",
"into",
"Go",
"type"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/types.go#L52-L70 |
12,653 | FDio/govpp | cmd/binapi-generator/parse.go | printPackage | func printPackage(pkg *Package) {
if len(pkg.Enums) > 0 {
logf("loaded %d enums:", len(pkg.Enums))
for k, enum := range pkg.Enums {
logf(" - enum #%d\t%+v", k, enum)
}
}
if len(pkg.Unions) > 0 {
logf("loaded %d unions:", len(pkg.Unions))
for k, union := range pkg.Unions {
logf(" - union #%d\t%+v", k, union)
}
}
if len(pkg.Types) > 0 {
logf("loaded %d types:", len(pkg.Types))
for _, typ := range pkg.Types {
logf(" - type: %q (%d fields)", typ.Name, len(typ.Fields))
}
}
if len(pkg.Messages) > 0 {
logf("loaded %d messages:", len(pkg.Messages))
for _, msg := range pkg.Messages {
logf(" - message: %q (%d fields)", msg.Name, len(msg.Fields))
}
}
if len(pkg.Services) > 0 {
logf("loaded %d services:", len(pkg.Services))
for _, svc := range pkg.Services {
var info string
if svc.Stream {
info = "(STREAM)"
} else if len(svc.Events) > 0 {
info = fmt.Sprintf("(EVENTS: %v)", svc.Events)
}
logf(" - service: %q -> %q %s", svc.RequestType, svc.ReplyType, info)
}
}
} | go | func printPackage(pkg *Package) {
if len(pkg.Enums) > 0 {
logf("loaded %d enums:", len(pkg.Enums))
for k, enum := range pkg.Enums {
logf(" - enum #%d\t%+v", k, enum)
}
}
if len(pkg.Unions) > 0 {
logf("loaded %d unions:", len(pkg.Unions))
for k, union := range pkg.Unions {
logf(" - union #%d\t%+v", k, union)
}
}
if len(pkg.Types) > 0 {
logf("loaded %d types:", len(pkg.Types))
for _, typ := range pkg.Types {
logf(" - type: %q (%d fields)", typ.Name, len(typ.Fields))
}
}
if len(pkg.Messages) > 0 {
logf("loaded %d messages:", len(pkg.Messages))
for _, msg := range pkg.Messages {
logf(" - message: %q (%d fields)", msg.Name, len(msg.Fields))
}
}
if len(pkg.Services) > 0 {
logf("loaded %d services:", len(pkg.Services))
for _, svc := range pkg.Services {
var info string
if svc.Stream {
info = "(STREAM)"
} else if len(svc.Events) > 0 {
info = fmt.Sprintf("(EVENTS: %v)", svc.Events)
}
logf(" - service: %q -> %q %s", svc.RequestType, svc.ReplyType, info)
}
}
} | [
"func",
"printPackage",
"(",
"pkg",
"*",
"Package",
")",
"{",
"if",
"len",
"(",
"pkg",
".",
"Enums",
")",
">",
"0",
"{",
"logf",
"(",
"\"",
"\"",
",",
"len",
"(",
"pkg",
".",
"Enums",
")",
")",
"\n",
"for",
"k",
",",
"enum",
":=",
"range",
"p... | // printPackage prints all loaded objects for package | [
"printPackage",
"prints",
"all",
"loaded",
"objects",
"for",
"package"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L200-L237 |
12,654 | FDio/govpp | cmd/binapi-generator/parse.go | parseEnum | func parseEnum(ctx *context, enumNode *jsongo.JSONNode) (*Enum, error) {
if enumNode.Len() == 0 || enumNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for enum specified")
}
enumName, ok := enumNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("enum name is %T, not a string", enumNode.At(0).Get())
}
enumType, ok := enumNode.At(enumNode.Len() - 1).At("enumtype").Get().(string)
if !ok {
return nil, fmt.Errorf("enum type invalid or missing")
}
enum := Enum{
Name: enumName,
Type: enumType,
}
// loop through enum entries, skip first (name) and last (enumtype)
for j := 1; j < enumNode.Len()-1; j++ {
if enumNode.At(j).GetType() == jsongo.TypeArray {
entry := enumNode.At(j)
if entry.Len() < 2 || entry.At(0).GetType() != jsongo.TypeValue || entry.At(1).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for enum entry specified")
}
entryName, ok := entry.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("enum entry name is %T, not a string", entry.At(0).Get())
}
entryVal := entry.At(1).Get()
enum.Entries = append(enum.Entries, EnumEntry{
Name: entryName,
Value: entryVal,
})
}
}
return &enum, nil
} | go | func parseEnum(ctx *context, enumNode *jsongo.JSONNode) (*Enum, error) {
if enumNode.Len() == 0 || enumNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for enum specified")
}
enumName, ok := enumNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("enum name is %T, not a string", enumNode.At(0).Get())
}
enumType, ok := enumNode.At(enumNode.Len() - 1).At("enumtype").Get().(string)
if !ok {
return nil, fmt.Errorf("enum type invalid or missing")
}
enum := Enum{
Name: enumName,
Type: enumType,
}
// loop through enum entries, skip first (name) and last (enumtype)
for j := 1; j < enumNode.Len()-1; j++ {
if enumNode.At(j).GetType() == jsongo.TypeArray {
entry := enumNode.At(j)
if entry.Len() < 2 || entry.At(0).GetType() != jsongo.TypeValue || entry.At(1).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for enum entry specified")
}
entryName, ok := entry.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("enum entry name is %T, not a string", entry.At(0).Get())
}
entryVal := entry.At(1).Get()
enum.Entries = append(enum.Entries, EnumEntry{
Name: entryName,
Value: entryVal,
})
}
}
return &enum, nil
} | [
"func",
"parseEnum",
"(",
"ctx",
"*",
"context",
",",
"enumNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Enum",
",",
"error",
")",
"{",
"if",
"enumNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"enumNode",
".",
"At",
"(",
"0",
")",
".",
... | // parseEnum parses VPP binary API enum object from JSON node | [
"parseEnum",
"parses",
"VPP",
"binary",
"API",
"enum",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L240-L282 |
12,655 | FDio/govpp | cmd/binapi-generator/parse.go | parseUnion | func parseUnion(ctx *context, unionNode *jsongo.JSONNode) (*Union, error) {
if unionNode.Len() == 0 || unionNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for union specified")
}
unionName, ok := unionNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("union name is %T, not a string", unionNode.At(0).Get())
}
unionCRC, ok := unionNode.At(unionNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("union crc invalid or missing")
}
union := Union{
Name: unionName,
CRC: unionCRC,
}
// loop through union fields, skip first (name) and last (crc)
for j := 1; j < unionNode.Len()-1; j++ {
if unionNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := unionNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
union.Fields = append(union.Fields, *field)
}
}
return &union, nil
} | go | func parseUnion(ctx *context, unionNode *jsongo.JSONNode) (*Union, error) {
if unionNode.Len() == 0 || unionNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for union specified")
}
unionName, ok := unionNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("union name is %T, not a string", unionNode.At(0).Get())
}
unionCRC, ok := unionNode.At(unionNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("union crc invalid or missing")
}
union := Union{
Name: unionName,
CRC: unionCRC,
}
// loop through union fields, skip first (name) and last (crc)
for j := 1; j < unionNode.Len()-1; j++ {
if unionNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := unionNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
union.Fields = append(union.Fields, *field)
}
}
return &union, nil
} | [
"func",
"parseUnion",
"(",
"ctx",
"*",
"context",
",",
"unionNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Union",
",",
"error",
")",
"{",
"if",
"unionNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"unionNode",
".",
"At",
"(",
"0",
")",
"... | // parseUnion parses VPP binary API union object from JSON node | [
"parseUnion",
"parses",
"VPP",
"binary",
"API",
"union",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L285-L319 |
12,656 | FDio/govpp | cmd/binapi-generator/parse.go | parseType | func parseType(ctx *context, typeNode *jsongo.JSONNode) (*Type, error) {
if typeNode.Len() == 0 || typeNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for type specified")
}
typeName, ok := typeNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("type name is %T, not a string", typeNode.At(0).Get())
}
typeCRC, ok := typeNode.At(typeNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("type crc invalid or missing")
}
typ := Type{
Name: typeName,
CRC: typeCRC,
}
// loop through type fields, skip first (name) and last (crc)
for j := 1; j < typeNode.Len()-1; j++ {
if typeNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := typeNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
typ.Fields = append(typ.Fields, *field)
}
}
return &typ, nil
} | go | func parseType(ctx *context, typeNode *jsongo.JSONNode) (*Type, error) {
if typeNode.Len() == 0 || typeNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for type specified")
}
typeName, ok := typeNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("type name is %T, not a string", typeNode.At(0).Get())
}
typeCRC, ok := typeNode.At(typeNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("type crc invalid or missing")
}
typ := Type{
Name: typeName,
CRC: typeCRC,
}
// loop through type fields, skip first (name) and last (crc)
for j := 1; j < typeNode.Len()-1; j++ {
if typeNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := typeNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
typ.Fields = append(typ.Fields, *field)
}
}
return &typ, nil
} | [
"func",
"parseType",
"(",
"ctx",
"*",
"context",
",",
"typeNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Type",
",",
"error",
")",
"{",
"if",
"typeNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"typeNode",
".",
"At",
"(",
"0",
")",
".",
... | // parseType parses VPP binary API type object from JSON node | [
"parseType",
"parses",
"VPP",
"binary",
"API",
"type",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L322-L356 |
12,657 | FDio/govpp | cmd/binapi-generator/parse.go | parseAlias | func parseAlias(ctx *context, aliasName string, aliasNode *jsongo.JSONNode) (*Alias, error) {
if aliasNode.Len() == 0 || aliasNode.At(aliasTypeField).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for alias specified")
}
alias := Alias{
Name: aliasName,
}
if typeNode := aliasNode.At(aliasTypeField); typeNode.GetType() == jsongo.TypeValue {
typ, ok := typeNode.Get().(string)
if !ok {
return nil, fmt.Errorf("alias type is %T, not a string", typeNode.Get())
}
if typ != "null" {
alias.Type = typ
}
}
if lengthNode := aliasNode.At(aliasLengthField); lengthNode.GetType() == jsongo.TypeValue {
length, ok := lengthNode.Get().(float64)
if !ok {
return nil, fmt.Errorf("alias length is %T, not a float64", lengthNode.Get())
}
alias.Length = int(length)
}
return &alias, nil
} | go | func parseAlias(ctx *context, aliasName string, aliasNode *jsongo.JSONNode) (*Alias, error) {
if aliasNode.Len() == 0 || aliasNode.At(aliasTypeField).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for alias specified")
}
alias := Alias{
Name: aliasName,
}
if typeNode := aliasNode.At(aliasTypeField); typeNode.GetType() == jsongo.TypeValue {
typ, ok := typeNode.Get().(string)
if !ok {
return nil, fmt.Errorf("alias type is %T, not a string", typeNode.Get())
}
if typ != "null" {
alias.Type = typ
}
}
if lengthNode := aliasNode.At(aliasLengthField); lengthNode.GetType() == jsongo.TypeValue {
length, ok := lengthNode.Get().(float64)
if !ok {
return nil, fmt.Errorf("alias length is %T, not a float64", lengthNode.Get())
}
alias.Length = int(length)
}
return &alias, nil
} | [
"func",
"parseAlias",
"(",
"ctx",
"*",
"context",
",",
"aliasName",
"string",
",",
"aliasNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Alias",
",",
"error",
")",
"{",
"if",
"aliasNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"aliasNode",
"."... | // parseAlias parses VPP binary API alias object from JSON node | [
"parseAlias",
"parses",
"VPP",
"binary",
"API",
"alias",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L359-L387 |
12,658 | FDio/govpp | cmd/binapi-generator/parse.go | parseMessage | func parseMessage(ctx *context, msgNode *jsongo.JSONNode) (*Message, error) {
if msgNode.Len() == 0 || msgNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for message specified")
}
msgName, ok := msgNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("message name is %T, not a string", msgNode.At(0).Get())
}
msgCRC, ok := msgNode.At(msgNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("message crc invalid or missing")
}
msg := Message{
Name: msgName,
CRC: msgCRC,
}
// loop through message fields, skip first (name) and last (crc)
for j := 1; j < msgNode.Len()-1; j++ {
if msgNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := msgNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
msg.Fields = append(msg.Fields, *field)
}
}
return &msg, nil
} | go | func parseMessage(ctx *context, msgNode *jsongo.JSONNode) (*Message, error) {
if msgNode.Len() == 0 || msgNode.At(0).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for message specified")
}
msgName, ok := msgNode.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("message name is %T, not a string", msgNode.At(0).Get())
}
msgCRC, ok := msgNode.At(msgNode.Len() - 1).At(crcField).Get().(string)
if !ok {
return nil, fmt.Errorf("message crc invalid or missing")
}
msg := Message{
Name: msgName,
CRC: msgCRC,
}
// loop through message fields, skip first (name) and last (crc)
for j := 1; j < msgNode.Len()-1; j++ {
if msgNode.At(j).GetType() == jsongo.TypeArray {
fieldNode := msgNode.At(j)
field, err := parseField(ctx, fieldNode)
if err != nil {
return nil, err
}
msg.Fields = append(msg.Fields, *field)
}
}
return &msg, nil
} | [
"func",
"parseMessage",
"(",
"ctx",
"*",
"context",
",",
"msgNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Message",
",",
"error",
")",
"{",
"if",
"msgNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"msgNode",
".",
"At",
"(",
"0",
")",
"."... | // parseMessage parses VPP binary API message object from JSON node | [
"parseMessage",
"parses",
"VPP",
"binary",
"API",
"message",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L390-L425 |
12,659 | FDio/govpp | cmd/binapi-generator/parse.go | parseField | func parseField(ctx *context, field *jsongo.JSONNode) (*Field, error) {
if field.Len() < 2 || field.At(0).GetType() != jsongo.TypeValue || field.At(1).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for field specified")
}
fieldType, ok := field.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("field type is %T, not a string", field.At(0).Get())
}
fieldName, ok := field.At(1).Get().(string)
if !ok {
return nil, fmt.Errorf("field name is %T, not a string", field.At(1).Get())
}
var fieldLength float64
if field.Len() >= 3 {
fieldLength, ok = field.At(2).Get().(float64)
if !ok {
return nil, fmt.Errorf("field length is %T, not float64", field.At(2).Get())
}
}
var fieldLengthFrom string
if field.Len() >= 4 {
fieldLengthFrom, ok = field.At(3).Get().(string)
if !ok {
return nil, fmt.Errorf("field length from is %T, not a string", field.At(3).Get())
}
}
return &Field{
Name: fieldName,
Type: fieldType,
Length: int(fieldLength),
SizeFrom: fieldLengthFrom,
}, nil
} | go | func parseField(ctx *context, field *jsongo.JSONNode) (*Field, error) {
if field.Len() < 2 || field.At(0).GetType() != jsongo.TypeValue || field.At(1).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for field specified")
}
fieldType, ok := field.At(0).Get().(string)
if !ok {
return nil, fmt.Errorf("field type is %T, not a string", field.At(0).Get())
}
fieldName, ok := field.At(1).Get().(string)
if !ok {
return nil, fmt.Errorf("field name is %T, not a string", field.At(1).Get())
}
var fieldLength float64
if field.Len() >= 3 {
fieldLength, ok = field.At(2).Get().(float64)
if !ok {
return nil, fmt.Errorf("field length is %T, not float64", field.At(2).Get())
}
}
var fieldLengthFrom string
if field.Len() >= 4 {
fieldLengthFrom, ok = field.At(3).Get().(string)
if !ok {
return nil, fmt.Errorf("field length from is %T, not a string", field.At(3).Get())
}
}
return &Field{
Name: fieldName,
Type: fieldType,
Length: int(fieldLength),
SizeFrom: fieldLengthFrom,
}, nil
} | [
"func",
"parseField",
"(",
"ctx",
"*",
"context",
",",
"field",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Field",
",",
"error",
")",
"{",
"if",
"field",
".",
"Len",
"(",
")",
"<",
"2",
"||",
"field",
".",
"At",
"(",
"0",
")",
".",
"GetTyp... | // parseField parses VPP binary API object field from JSON node | [
"parseField",
"parses",
"VPP",
"binary",
"API",
"object",
"field",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L428-L462 |
12,660 | FDio/govpp | cmd/binapi-generator/parse.go | parseService | func parseService(ctx *context, svcName string, svcNode *jsongo.JSONNode) (*Service, error) {
if svcNode.Len() == 0 || svcNode.At(replyField).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for service specified")
}
svc := Service{
Name: ctx.moduleName + "." + svcName,
RequestType: svcName,
}
if replyNode := svcNode.At(replyField); replyNode.GetType() == jsongo.TypeValue {
reply, ok := replyNode.Get().(string)
if !ok {
return nil, fmt.Errorf("service reply is %T, not a string", replyNode.Get())
}
if reply != serviceNoReply {
svc.ReplyType = reply
}
}
// stream service (dumps)
if streamNode := svcNode.At(streamField); streamNode.GetType() == jsongo.TypeValue {
var ok bool
svc.Stream, ok = streamNode.Get().(bool)
if !ok {
return nil, fmt.Errorf("service stream is %T, not a string", streamNode.Get())
}
}
// events service (event subscription)
if eventsNode := svcNode.At(eventsField); eventsNode.GetType() == jsongo.TypeArray {
for j := 0; j < eventsNode.Len(); j++ {
event := eventsNode.At(j).Get().(string)
svc.Events = append(svc.Events, event)
}
}
// validate service
if len(svc.Events) > 0 {
// EVENT service
if !strings.HasPrefix(svc.RequestType, serviceEventPrefix) {
log.Debugf("unusual EVENTS service: %+v\n"+
"- events service %q does not have %q prefix in request.",
svc, svc.Name, serviceEventPrefix)
}
} else if svc.Stream {
// STREAM service
if !strings.HasSuffix(svc.RequestType, serviceDumpSuffix) ||
!strings.HasSuffix(svc.ReplyType, serviceDetailsSuffix) {
log.Debugf("unusual STREAM service: %+v\n"+
"- stream service %q does not have %q suffix in request or reply does not have %q suffix.",
svc, svc.Name, serviceDumpSuffix, serviceDetailsSuffix)
}
} else if svc.ReplyType != "" && svc.ReplyType != serviceNoReply {
// REQUEST service
// some messages might have `null` reply (for example: memclnt)
if !strings.HasSuffix(svc.ReplyType, serviceReplySuffix) {
log.Debugf("unusual REQUEST service: %+v\n"+
"- service %q does not have %q suffix in reply.",
svc, svc.Name, serviceReplySuffix)
}
}
return &svc, nil
} | go | func parseService(ctx *context, svcName string, svcNode *jsongo.JSONNode) (*Service, error) {
if svcNode.Len() == 0 || svcNode.At(replyField).GetType() != jsongo.TypeValue {
return nil, errors.New("invalid JSON for service specified")
}
svc := Service{
Name: ctx.moduleName + "." + svcName,
RequestType: svcName,
}
if replyNode := svcNode.At(replyField); replyNode.GetType() == jsongo.TypeValue {
reply, ok := replyNode.Get().(string)
if !ok {
return nil, fmt.Errorf("service reply is %T, not a string", replyNode.Get())
}
if reply != serviceNoReply {
svc.ReplyType = reply
}
}
// stream service (dumps)
if streamNode := svcNode.At(streamField); streamNode.GetType() == jsongo.TypeValue {
var ok bool
svc.Stream, ok = streamNode.Get().(bool)
if !ok {
return nil, fmt.Errorf("service stream is %T, not a string", streamNode.Get())
}
}
// events service (event subscription)
if eventsNode := svcNode.At(eventsField); eventsNode.GetType() == jsongo.TypeArray {
for j := 0; j < eventsNode.Len(); j++ {
event := eventsNode.At(j).Get().(string)
svc.Events = append(svc.Events, event)
}
}
// validate service
if len(svc.Events) > 0 {
// EVENT service
if !strings.HasPrefix(svc.RequestType, serviceEventPrefix) {
log.Debugf("unusual EVENTS service: %+v\n"+
"- events service %q does not have %q prefix in request.",
svc, svc.Name, serviceEventPrefix)
}
} else if svc.Stream {
// STREAM service
if !strings.HasSuffix(svc.RequestType, serviceDumpSuffix) ||
!strings.HasSuffix(svc.ReplyType, serviceDetailsSuffix) {
log.Debugf("unusual STREAM service: %+v\n"+
"- stream service %q does not have %q suffix in request or reply does not have %q suffix.",
svc, svc.Name, serviceDumpSuffix, serviceDetailsSuffix)
}
} else if svc.ReplyType != "" && svc.ReplyType != serviceNoReply {
// REQUEST service
// some messages might have `null` reply (for example: memclnt)
if !strings.HasSuffix(svc.ReplyType, serviceReplySuffix) {
log.Debugf("unusual REQUEST service: %+v\n"+
"- service %q does not have %q suffix in reply.",
svc, svc.Name, serviceReplySuffix)
}
}
return &svc, nil
} | [
"func",
"parseService",
"(",
"ctx",
"*",
"context",
",",
"svcName",
"string",
",",
"svcNode",
"*",
"jsongo",
".",
"JSONNode",
")",
"(",
"*",
"Service",
",",
"error",
")",
"{",
"if",
"svcNode",
".",
"Len",
"(",
")",
"==",
"0",
"||",
"svcNode",
".",
... | // parseService parses VPP binary API service object from JSON node | [
"parseService",
"parses",
"VPP",
"binary",
"API",
"service",
"object",
"from",
"JSON",
"node"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/parse.go#L465-L529 |
12,661 | FDio/govpp | adapter/socketclient/socketclient.go | WaitReady | func (c *vppClient) WaitReady() error {
// check if file at the path already exists
if _, err := os.Stat(c.sockAddr); err == nil {
return nil
} else if os.IsExist(err) {
return err
}
// if not, watch for it
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer func() {
if err := watcher.Close(); err != nil {
Log.Errorf("failed to close file watcher: %v", err)
}
}()
// start watching directory
if err := watcher.Add(filepath.Dir(c.sockAddr)); err != nil {
return err
}
for {
select {
case <-time.After(MaxWaitReady):
return fmt.Errorf("waiting for socket file timed out (%s)", MaxWaitReady)
case e := <-watcher.Errors:
return e
case ev := <-watcher.Events:
Log.Debugf("watcher event: %+v", ev)
if ev.Name == c.sockAddr {
if (ev.Op & fsnotify.Create) == fsnotify.Create {
// socket was created, we are ready
return nil
}
}
}
}
} | go | func (c *vppClient) WaitReady() error {
// check if file at the path already exists
if _, err := os.Stat(c.sockAddr); err == nil {
return nil
} else if os.IsExist(err) {
return err
}
// if not, watch for it
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer func() {
if err := watcher.Close(); err != nil {
Log.Errorf("failed to close file watcher: %v", err)
}
}()
// start watching directory
if err := watcher.Add(filepath.Dir(c.sockAddr)); err != nil {
return err
}
for {
select {
case <-time.After(MaxWaitReady):
return fmt.Errorf("waiting for socket file timed out (%s)", MaxWaitReady)
case e := <-watcher.Errors:
return e
case ev := <-watcher.Events:
Log.Debugf("watcher event: %+v", ev)
if ev.Name == c.sockAddr {
if (ev.Op & fsnotify.Create) == fsnotify.Create {
// socket was created, we are ready
return nil
}
}
}
}
} | [
"func",
"(",
"c",
"*",
"vppClient",
")",
"WaitReady",
"(",
")",
"error",
"{",
"// check if file at the path already exists",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"c",
".",
"sockAddr",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"nil",
... | // WaitReady checks socket file existence and waits for it if necessary | [
"WaitReady",
"checks",
"socket",
"file",
"existence",
"and",
"waits",
"for",
"it",
"if",
"necessary"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/socketclient/socketclient.go#L102-L142 |
12,662 | FDio/govpp | examples/simple-client/simple_client.go | aclVersion | func aclVersion(ch api.Channel) {
fmt.Println("ACL getting version")
req := &acl.ACLPluginGetVersion{}
reply := &acl.ACLPluginGetVersionReply{}
if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
fmt.Println("ERROR:", err)
} else {
fmt.Printf("ACL version reply: %+v\n", reply)
}
} | go | func aclVersion(ch api.Channel) {
fmt.Println("ACL getting version")
req := &acl.ACLPluginGetVersion{}
reply := &acl.ACLPluginGetVersionReply{}
if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
fmt.Println("ERROR:", err)
} else {
fmt.Printf("ACL version reply: %+v\n", reply)
}
} | [
"func",
"aclVersion",
"(",
"ch",
"api",
".",
"Channel",
")",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n\n",
"req",
":=",
"&",
"acl",
".",
"ACLPluginGetVersion",
"{",
"}",
"\n",
"reply",
":=",
"&",
"acl",
".",
"ACLPluginGetVersionReply",
"{",... | // aclVersion is the simplest API example - one empty request message and one reply message. | [
"aclVersion",
"is",
"the",
"simplest",
"API",
"example",
"-",
"one",
"empty",
"request",
"message",
"and",
"one",
"reply",
"message",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/examples/simple-client/simple_client.go#L73-L84 |
12,663 | FDio/govpp | examples/simple-client/simple_client.go | aclConfig | func aclConfig(ch api.Channel) {
fmt.Println("ACL adding replace")
req := &acl.ACLAddReplace{
ACLIndex: ^uint32(0),
Tag: []byte("access list 1"),
R: []acl.ACLRule{
{
IsPermit: 1,
SrcIPAddr: net.ParseIP("10.0.0.0").To4(),
SrcIPPrefixLen: 8,
DstIPAddr: net.ParseIP("192.168.1.0").To4(),
DstIPPrefixLen: 24,
Proto: 6,
},
{
IsPermit: 1,
SrcIPAddr: net.ParseIP("8.8.8.8").To4(),
SrcIPPrefixLen: 32,
DstIPAddr: net.ParseIP("172.16.0.0").To4(),
DstIPPrefixLen: 16,
Proto: 6,
},
},
}
reply := &acl.ACLAddReplaceReply{}
if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
fmt.Println("ERROR:", err)
return
}
if reply.Retval != 0 {
fmt.Println("Retval:", reply.Retval)
return
}
fmt.Printf("ACL add replace reply: %+v\n", reply)
} | go | func aclConfig(ch api.Channel) {
fmt.Println("ACL adding replace")
req := &acl.ACLAddReplace{
ACLIndex: ^uint32(0),
Tag: []byte("access list 1"),
R: []acl.ACLRule{
{
IsPermit: 1,
SrcIPAddr: net.ParseIP("10.0.0.0").To4(),
SrcIPPrefixLen: 8,
DstIPAddr: net.ParseIP("192.168.1.0").To4(),
DstIPPrefixLen: 24,
Proto: 6,
},
{
IsPermit: 1,
SrcIPAddr: net.ParseIP("8.8.8.8").To4(),
SrcIPPrefixLen: 32,
DstIPAddr: net.ParseIP("172.16.0.0").To4(),
DstIPPrefixLen: 16,
Proto: 6,
},
},
}
reply := &acl.ACLAddReplaceReply{}
if err := ch.SendRequest(req).ReceiveReply(reply); err != nil {
fmt.Println("ERROR:", err)
return
}
if reply.Retval != 0 {
fmt.Println("Retval:", reply.Retval)
return
}
fmt.Printf("ACL add replace reply: %+v\n", reply)
} | [
"func",
"aclConfig",
"(",
"ch",
"api",
".",
"Channel",
")",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n\n",
"req",
":=",
"&",
"acl",
".",
"ACLAddReplace",
"{",
"ACLIndex",
":",
"^",
"uint32",
"(",
"0",
")",
",",
"Tag",
":",
"[",
"]",
... | // aclConfig is another simple API example - in this case, the request contains structured data. | [
"aclConfig",
"is",
"another",
"simple",
"API",
"example",
"-",
"in",
"this",
"case",
"the",
"request",
"contains",
"structured",
"data",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/examples/simple-client/simple_client.go#L87-L125 |
12,664 | FDio/govpp | examples/simple-client/simple_client.go | interfaceNotifications | func interfaceNotifications(ch api.Channel) {
fmt.Println("Subscribing to notificaiton events")
notifChan := make(chan api.Message, 100)
// subscribe for specific notification message
sub, err := ch.SubscribeNotification(notifChan, &interfaces.SwInterfaceEvent{})
if err != nil {
panic(err)
}
// enable interface events in VPP
err = ch.SendRequest(&interfaces.WantInterfaceEvents{
PID: uint32(os.Getpid()),
EnableDisable: 1,
}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})
if err != nil {
panic(err)
}
// generate some events in VPP
err = ch.SendRequest(&interfaces.SwInterfaceSetFlags{
SwIfIndex: 0,
AdminUpDown: 0,
}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})
if err != nil {
panic(err)
}
err = ch.SendRequest(&interfaces.SwInterfaceSetFlags{
SwIfIndex: 0,
AdminUpDown: 1,
}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})
if err != nil {
panic(err)
}
// receive one notification
notif := (<-notifChan).(*interfaces.SwInterfaceEvent)
fmt.Printf("incoming event: %+v\n", notif)
// disable interface events in VPP
err = ch.SendRequest(&interfaces.WantInterfaceEvents{
PID: uint32(os.Getpid()),
EnableDisable: 0,
}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})
if err != nil {
panic(err)
}
// unsubscribe from delivery of the notifications
err = sub.Unsubscribe()
if err != nil {
panic(err)
}
} | go | func interfaceNotifications(ch api.Channel) {
fmt.Println("Subscribing to notificaiton events")
notifChan := make(chan api.Message, 100)
// subscribe for specific notification message
sub, err := ch.SubscribeNotification(notifChan, &interfaces.SwInterfaceEvent{})
if err != nil {
panic(err)
}
// enable interface events in VPP
err = ch.SendRequest(&interfaces.WantInterfaceEvents{
PID: uint32(os.Getpid()),
EnableDisable: 1,
}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})
if err != nil {
panic(err)
}
// generate some events in VPP
err = ch.SendRequest(&interfaces.SwInterfaceSetFlags{
SwIfIndex: 0,
AdminUpDown: 0,
}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})
if err != nil {
panic(err)
}
err = ch.SendRequest(&interfaces.SwInterfaceSetFlags{
SwIfIndex: 0,
AdminUpDown: 1,
}).ReceiveReply(&interfaces.SwInterfaceSetFlagsReply{})
if err != nil {
panic(err)
}
// receive one notification
notif := (<-notifChan).(*interfaces.SwInterfaceEvent)
fmt.Printf("incoming event: %+v\n", notif)
// disable interface events in VPP
err = ch.SendRequest(&interfaces.WantInterfaceEvents{
PID: uint32(os.Getpid()),
EnableDisable: 0,
}).ReceiveReply(&interfaces.WantInterfaceEventsReply{})
if err != nil {
panic(err)
}
// unsubscribe from delivery of the notifications
err = sub.Unsubscribe()
if err != nil {
panic(err)
}
} | [
"func",
"interfaceNotifications",
"(",
"ch",
"api",
".",
"Channel",
")",
"{",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n\n",
"notifChan",
":=",
"make",
"(",
"chan",
"api",
".",
"Message",
",",
"100",
")",
"\n\n",
"// subscribe for specific notification... | // interfaceNotifications shows the usage of notification API. Note that for notifications,
// you are supposed to create your own Go channel with your preferred buffer size. If the channel's
// buffer is full, the notifications will not be delivered into it. | [
"interfaceNotifications",
"shows",
"the",
"usage",
"of",
"notification",
"API",
".",
"Note",
"that",
"for",
"notifications",
"you",
"are",
"supposed",
"to",
"create",
"your",
"own",
"Go",
"channel",
"with",
"your",
"preferred",
"buffer",
"size",
".",
"If",
"th... | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/examples/simple-client/simple_client.go#L225-L279 |
12,665 | FDio/govpp | cmd/binapi-generator/main.go | getInputFiles | func getInputFiles(inputDir string) (res []string, err error) {
files, err := ioutil.ReadDir(inputDir)
if err != nil {
return nil, fmt.Errorf("reading directory %s failed: %v", inputDir, err)
}
for _, f := range files {
if strings.HasSuffix(f.Name(), inputFileExt) {
res = append(res, filepath.Join(inputDir, f.Name()))
}
}
return res, nil
} | go | func getInputFiles(inputDir string) (res []string, err error) {
files, err := ioutil.ReadDir(inputDir)
if err != nil {
return nil, fmt.Errorf("reading directory %s failed: %v", inputDir, err)
}
for _, f := range files {
if strings.HasSuffix(f.Name(), inputFileExt) {
res = append(res, filepath.Join(inputDir, f.Name()))
}
}
return res, nil
} | [
"func",
"getInputFiles",
"(",
"inputDir",
"string",
")",
"(",
"res",
"[",
"]",
"string",
",",
"err",
"error",
")",
"{",
"files",
",",
"err",
":=",
"ioutil",
".",
"ReadDir",
"(",
"inputDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
... | // getInputFiles returns all input files located in specified directory | [
"getInputFiles",
"returns",
"all",
"input",
"files",
"located",
"in",
"specified",
"directory"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/main.go#L85-L96 |
12,666 | FDio/govpp | cmd/binapi-generator/main.go | generateFromFile | func generateFromFile(inputFile, outputDir string) error {
logf("generating from file: %q", inputFile)
defer logf("--------------------------------------")
ctx, err := getContext(inputFile, outputDir)
if err != nil {
return err
}
ctx.includeAPIVersionCrc = *includeAPIVer
ctx.includeComments = *includeComments
// read input file contents
ctx.inputData, err = readFile(inputFile)
if err != nil {
return err
}
// parse JSON data into objects
jsonRoot, err := parseJSON(ctx.inputData)
if err != nil {
return err
}
ctx.packageData, err = parsePackage(ctx, jsonRoot)
if err != nil {
return err
}
// create output directory
packageDir := filepath.Dir(ctx.outputFile)
if err := os.MkdirAll(packageDir, 0777); err != nil {
return fmt.Errorf("creating output directory %q failed: %v", packageDir, err)
}
// open output file
f, err := os.Create(ctx.outputFile)
if err != nil {
return fmt.Errorf("creating output file %q failed: %v", ctx.outputFile, err)
}
defer f.Close()
// generate Go package code
w := bufio.NewWriter(f)
if err := generatePackage(ctx, w); err != nil {
return err
}
// go format the output file (fail probably means the output is not compilable)
cmd := exec.Command("gofmt", "-w", ctx.outputFile)
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("gofmt failed: %v\n%s", err, string(output))
}
// count number of lines in generated output file
cmd = exec.Command("wc", "-l", ctx.outputFile)
if output, err := cmd.CombinedOutput(); err != nil {
log.Warnf("wc command failed: %v\n%s", err, string(output))
} else {
logf("generated lines: %s", output)
}
return nil
} | go | func generateFromFile(inputFile, outputDir string) error {
logf("generating from file: %q", inputFile)
defer logf("--------------------------------------")
ctx, err := getContext(inputFile, outputDir)
if err != nil {
return err
}
ctx.includeAPIVersionCrc = *includeAPIVer
ctx.includeComments = *includeComments
// read input file contents
ctx.inputData, err = readFile(inputFile)
if err != nil {
return err
}
// parse JSON data into objects
jsonRoot, err := parseJSON(ctx.inputData)
if err != nil {
return err
}
ctx.packageData, err = parsePackage(ctx, jsonRoot)
if err != nil {
return err
}
// create output directory
packageDir := filepath.Dir(ctx.outputFile)
if err := os.MkdirAll(packageDir, 0777); err != nil {
return fmt.Errorf("creating output directory %q failed: %v", packageDir, err)
}
// open output file
f, err := os.Create(ctx.outputFile)
if err != nil {
return fmt.Errorf("creating output file %q failed: %v", ctx.outputFile, err)
}
defer f.Close()
// generate Go package code
w := bufio.NewWriter(f)
if err := generatePackage(ctx, w); err != nil {
return err
}
// go format the output file (fail probably means the output is not compilable)
cmd := exec.Command("gofmt", "-w", ctx.outputFile)
if output, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("gofmt failed: %v\n%s", err, string(output))
}
// count number of lines in generated output file
cmd = exec.Command("wc", "-l", ctx.outputFile)
if output, err := cmd.CombinedOutput(); err != nil {
log.Warnf("wc command failed: %v\n%s", err, string(output))
} else {
logf("generated lines: %s", output)
}
return nil
} | [
"func",
"generateFromFile",
"(",
"inputFile",
",",
"outputDir",
"string",
")",
"error",
"{",
"logf",
"(",
"\"",
"\"",
",",
"inputFile",
")",
"\n",
"defer",
"logf",
"(",
"\"",
"\"",
")",
"\n\n",
"ctx",
",",
"err",
":=",
"getContext",
"(",
"inputFile",
"... | // generateFromFile generates Go package from one input JSON file | [
"generateFromFile",
"generates",
"Go",
"package",
"from",
"one",
"input",
"JSON",
"file"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/main.go#L99-L159 |
12,667 | FDio/govpp | cmd/binapi-generator/main.go | readFile | func readFile(inputFile string) ([]byte, error) {
inputData, err := ioutil.ReadFile(inputFile)
if err != nil {
return nil, fmt.Errorf("reading data from file failed: %v", err)
}
return inputData, nil
} | go | func readFile(inputFile string) ([]byte, error) {
inputData, err := ioutil.ReadFile(inputFile)
if err != nil {
return nil, fmt.Errorf("reading data from file failed: %v", err)
}
return inputData, nil
} | [
"func",
"readFile",
"(",
"inputFile",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"inputData",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"inputFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
"... | // readFile reads content of a file into memory | [
"readFile",
"reads",
"content",
"of",
"a",
"file",
"into",
"memory"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/main.go#L162-L169 |
12,668 | FDio/govpp | cmd/binapi-generator/main.go | parseJSON | func parseJSON(inputData []byte) (*jsongo.JSONNode, error) {
root := jsongo.JSONNode{}
if err := json.Unmarshal(inputData, &root); err != nil {
return nil, fmt.Errorf("unmarshalling JSON failed: %v", err)
}
return &root, nil
} | go | func parseJSON(inputData []byte) (*jsongo.JSONNode, error) {
root := jsongo.JSONNode{}
if err := json.Unmarshal(inputData, &root); err != nil {
return nil, fmt.Errorf("unmarshalling JSON failed: %v", err)
}
return &root, nil
} | [
"func",
"parseJSON",
"(",
"inputData",
"[",
"]",
"byte",
")",
"(",
"*",
"jsongo",
".",
"JSONNode",
",",
"error",
")",
"{",
"root",
":=",
"jsongo",
".",
"JSONNode",
"{",
"}",
"\n\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"inputData",
",",
... | // parseJSON parses a JSON data into an in-memory tree | [
"parseJSON",
"parses",
"a",
"JSON",
"data",
"into",
"an",
"in",
"-",
"memory",
"tree"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/cmd/binapi-generator/main.go#L172-L180 |
12,669 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | NewVppAdapter | func NewVppAdapter() *VppAdapter {
a := &VppAdapter{
msgIDSeq: 1000,
msgIDsToName: make(map[uint16]string),
msgNameToIds: make(map[string]uint16),
binAPITypes: make(map[string]reflect.Type),
}
a.registerBinAPITypes()
return a
} | go | func NewVppAdapter() *VppAdapter {
a := &VppAdapter{
msgIDSeq: 1000,
msgIDsToName: make(map[uint16]string),
msgNameToIds: make(map[string]uint16),
binAPITypes: make(map[string]reflect.Type),
}
a.registerBinAPITypes()
return a
} | [
"func",
"NewVppAdapter",
"(",
")",
"*",
"VppAdapter",
"{",
"a",
":=",
"&",
"VppAdapter",
"{",
"msgIDSeq",
":",
"1000",
",",
"msgIDsToName",
":",
"make",
"(",
"map",
"[",
"uint16",
"]",
"string",
")",
",",
"msgNameToIds",
":",
"make",
"(",
"map",
"[",
... | // NewVppAdapter returns a new mock adapter. | [
"NewVppAdapter",
"returns",
"a",
"new",
"mock",
"adapter",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L93-L102 |
12,670 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | GetMsgNameByID | func (a *VppAdapter) GetMsgNameByID(msgID uint16) (string, bool) {
switch msgID {
case 100:
return "control_ping", true
case 101:
return "control_ping_reply", true
case 200:
return "sw_interface_dump", true
case 201:
return "sw_interface_details", true
}
a.access.Lock()
defer a.access.Unlock()
msgName, found := a.msgIDsToName[msgID]
return msgName, found
} | go | func (a *VppAdapter) GetMsgNameByID(msgID uint16) (string, bool) {
switch msgID {
case 100:
return "control_ping", true
case 101:
return "control_ping_reply", true
case 200:
return "sw_interface_dump", true
case 201:
return "sw_interface_details", true
}
a.access.Lock()
defer a.access.Unlock()
msgName, found := a.msgIDsToName[msgID]
return msgName, found
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"GetMsgNameByID",
"(",
"msgID",
"uint16",
")",
"(",
"string",
",",
"bool",
")",
"{",
"switch",
"msgID",
"{",
"case",
"100",
":",
"return",
"\"",
"\"",
",",
"true",
"\n",
"case",
"101",
":",
"return",
"\"",
... | // GetMsgNameByID returns message name for specified message ID. | [
"GetMsgNameByID",
"returns",
"message",
"name",
"for",
"specified",
"message",
"ID",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L115-L132 |
12,671 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | ReplyTypeFor | func (a *VppAdapter) ReplyTypeFor(requestMsgName string) (reflect.Type, uint16, bool) {
replyName, foundName := binapi.ReplyNameFor(requestMsgName)
if foundName {
if reply, found := a.binAPITypes[replyName]; found {
msgID, err := a.GetMsgID(replyName, "")
if err == nil {
return reply, msgID, found
}
}
}
return nil, 0, false
} | go | func (a *VppAdapter) ReplyTypeFor(requestMsgName string) (reflect.Type, uint16, bool) {
replyName, foundName := binapi.ReplyNameFor(requestMsgName)
if foundName {
if reply, found := a.binAPITypes[replyName]; found {
msgID, err := a.GetMsgID(replyName, "")
if err == nil {
return reply, msgID, found
}
}
}
return nil, 0, false
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"ReplyTypeFor",
"(",
"requestMsgName",
"string",
")",
"(",
"reflect",
".",
"Type",
",",
"uint16",
",",
"bool",
")",
"{",
"replyName",
",",
"foundName",
":=",
"binapi",
".",
"ReplyNameFor",
"(",
"requestMsgName",
")... | // ReplyTypeFor returns reply message type for given request message name. | [
"ReplyTypeFor",
"returns",
"reply",
"message",
"type",
"for",
"given",
"request",
"message",
"name",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L143-L155 |
12,672 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | ReplyFor | func (a *VppAdapter) ReplyFor(requestMsgName string) (api.Message, uint16, bool) {
replType, msgID, foundReplType := a.ReplyTypeFor(requestMsgName)
if foundReplType {
msgVal := reflect.New(replType)
if msg, ok := msgVal.Interface().(api.Message); ok {
log.Println("FFF ", replType, msgID, foundReplType)
return msg, msgID, true
}
}
return nil, 0, false
} | go | func (a *VppAdapter) ReplyFor(requestMsgName string) (api.Message, uint16, bool) {
replType, msgID, foundReplType := a.ReplyTypeFor(requestMsgName)
if foundReplType {
msgVal := reflect.New(replType)
if msg, ok := msgVal.Interface().(api.Message); ok {
log.Println("FFF ", replType, msgID, foundReplType)
return msg, msgID, true
}
}
return nil, 0, false
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"ReplyFor",
"(",
"requestMsgName",
"string",
")",
"(",
"api",
".",
"Message",
",",
"uint16",
",",
"bool",
")",
"{",
"replType",
",",
"msgID",
",",
"foundReplType",
":=",
"a",
".",
"ReplyTypeFor",
"(",
"requestMsg... | // ReplyFor returns reply message for given request message name. | [
"ReplyFor",
"returns",
"reply",
"message",
"for",
"given",
"request",
"message",
"name",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L158-L169 |
12,673 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | ReplyBytes | func (a *VppAdapter) ReplyBytes(request MessageDTO, reply api.Message) ([]byte, error) {
replyMsgID, err := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
if err != nil {
log.Println("ReplyBytesE ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID,
" ", err)
return nil, err
}
log.Println("ReplyBytes ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID)
buf := new(bytes.Buffer)
err = struc.Pack(buf, &codec.VppReplyHeader{
VlMsgID: replyMsgID,
Context: request.ClientID,
})
if err != nil {
return nil, err
}
if err = struc.Pack(buf, reply); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func (a *VppAdapter) ReplyBytes(request MessageDTO, reply api.Message) ([]byte, error) {
replyMsgID, err := a.GetMsgID(reply.GetMessageName(), reply.GetCrcString())
if err != nil {
log.Println("ReplyBytesE ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID,
" ", err)
return nil, err
}
log.Println("ReplyBytes ", replyMsgID, " ", reply.GetMessageName(), " clientId: ", request.ClientID)
buf := new(bytes.Buffer)
err = struc.Pack(buf, &codec.VppReplyHeader{
VlMsgID: replyMsgID,
Context: request.ClientID,
})
if err != nil {
return nil, err
}
if err = struc.Pack(buf, reply); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"ReplyBytes",
"(",
"request",
"MessageDTO",
",",
"reply",
"api",
".",
"Message",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"replyMsgID",
",",
"err",
":=",
"a",
".",
"GetMsgID",
"(",
"reply",
".",
... | // ReplyBytes encodes the mocked reply into binary format. | [
"ReplyBytes",
"encodes",
"the",
"mocked",
"reply",
"into",
"binary",
"format",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L172-L194 |
12,674 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | GetMsgID | func (a *VppAdapter) GetMsgID(msgName string, msgCrc string) (uint16, error) {
switch msgName {
case "control_ping":
return 100, nil
case "control_ping_reply":
return 101, nil
case "sw_interface_dump":
return 200, nil
case "sw_interface_details":
return 201, nil
}
a.access.Lock()
defer a.access.Unlock()
msgID, found := a.msgNameToIds[msgName]
if found {
return msgID, nil
}
a.msgIDSeq++
msgID = a.msgIDSeq
a.msgNameToIds[msgName] = msgID
a.msgIDsToName[msgID] = msgName
return msgID, nil
} | go | func (a *VppAdapter) GetMsgID(msgName string, msgCrc string) (uint16, error) {
switch msgName {
case "control_ping":
return 100, nil
case "control_ping_reply":
return 101, nil
case "sw_interface_dump":
return 200, nil
case "sw_interface_details":
return 201, nil
}
a.access.Lock()
defer a.access.Unlock()
msgID, found := a.msgNameToIds[msgName]
if found {
return msgID, nil
}
a.msgIDSeq++
msgID = a.msgIDSeq
a.msgNameToIds[msgName] = msgID
a.msgIDsToName[msgID] = msgName
return msgID, nil
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"GetMsgID",
"(",
"msgName",
"string",
",",
"msgCrc",
"string",
")",
"(",
"uint16",
",",
"error",
")",
"{",
"switch",
"msgName",
"{",
"case",
"\"",
"\"",
":",
"return",
"100",
",",
"nil",
"\n",
"case",
"\"",
... | // GetMsgID returns mocked message ID for the given message name and CRC. | [
"GetMsgID",
"returns",
"mocked",
"message",
"ID",
"for",
"the",
"given",
"message",
"name",
"and",
"CRC",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L197-L223 |
12,675 | FDio/govpp | adapter/mock/mock_vpp_adapter.go | MockReplyHandler | func (a *VppAdapter) MockReplyHandler(replyHandler ReplyHandler) {
a.repliesLock.Lock()
defer a.repliesLock.Unlock()
a.replyHandlers = append(a.replyHandlers, replyHandler)
a.mode = useReplyHandlers
} | go | func (a *VppAdapter) MockReplyHandler(replyHandler ReplyHandler) {
a.repliesLock.Lock()
defer a.repliesLock.Unlock()
a.replyHandlers = append(a.replyHandlers, replyHandler)
a.mode = useReplyHandlers
} | [
"func",
"(",
"a",
"*",
"VppAdapter",
")",
"MockReplyHandler",
"(",
"replyHandler",
"ReplyHandler",
")",
"{",
"a",
".",
"repliesLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"repliesLock",
".",
"Unlock",
"(",
")",
"\n\n",
"a",
".",
"replyHandlers... | // MockReplyHandler registers a handler function that is supposed to generate mock responses to incoming requests.
// Using of this method automatically switches the mock into th useReplyHandlers mode. | [
"MockReplyHandler",
"registers",
"a",
"handler",
"function",
"that",
"is",
"supposed",
"to",
"generate",
"mock",
"responses",
"to",
"incoming",
"requests",
".",
"Using",
"of",
"this",
"method",
"automatically",
"switches",
"the",
"mock",
"into",
"th",
"useReplyHan... | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/adapter/mock/mock_vpp_adapter.go#L367-L373 |
12,676 | FDio/govpp | extras/libmemif/examples/gopacket/gopacket.go | OnInterrupt | func OnInterrupt(handle *libmemif.MemifPacketHandle) {
source := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
var responses []gopacket.Packet
// Process ICMP pings
for packet := range source.Packets() {
fmt.Println("Received new packet:")
fmt.Println(packet.Dump())
response, err := GeneratePacketResponse(packet)
if err != nil {
fmt.Printf("Failed to generate response: %v\n", err)
continue
}
fmt.Println("Sending response:")
fmt.Println(response.Dump())
responses = append(responses, response)
}
// Answer with ICMP pongs
for i, response := range responses {
err := handle.WritePacketData(response.Data())
switch err {
case io.EOF:
return
case nil:
fmt.Printf("Succesfully sent packet #%v %v\n", i, len(response.Data()))
default:
fmt.Printf("Got error while sending packet #%v %v\n", i, err)
}
}
} | go | func OnInterrupt(handle *libmemif.MemifPacketHandle) {
source := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
var responses []gopacket.Packet
// Process ICMP pings
for packet := range source.Packets() {
fmt.Println("Received new packet:")
fmt.Println(packet.Dump())
response, err := GeneratePacketResponse(packet)
if err != nil {
fmt.Printf("Failed to generate response: %v\n", err)
continue
}
fmt.Println("Sending response:")
fmt.Println(response.Dump())
responses = append(responses, response)
}
// Answer with ICMP pongs
for i, response := range responses {
err := handle.WritePacketData(response.Data())
switch err {
case io.EOF:
return
case nil:
fmt.Printf("Succesfully sent packet #%v %v\n", i, len(response.Data()))
default:
fmt.Printf("Got error while sending packet #%v %v\n", i, err)
}
}
} | [
"func",
"OnInterrupt",
"(",
"handle",
"*",
"libmemif",
".",
"MemifPacketHandle",
")",
"{",
"source",
":=",
"gopacket",
".",
"NewPacketSource",
"(",
"handle",
",",
"layers",
".",
"LayerTypeEthernet",
")",
"\n",
"var",
"responses",
"[",
"]",
"gopacket",
".",
"... | // OnInterrupt is called when interrupted | [
"OnInterrupt",
"is",
"called",
"when",
"interrupted"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/examples/gopacket/gopacket.go#L107-L140 |
12,677 | FDio/govpp | extras/libmemif/examples/gopacket/gopacket.go | CreateInterruptCallback | func CreateInterruptCallback(handle *libmemif.MemifPacketHandle, interruptCh <-chan struct{}, callback func(handle *libmemif.MemifPacketHandle)) {
for {
select {
case <-interruptCh:
callback(handle)
case <-stopCh:
handle.Close()
return
}
}
} | go | func CreateInterruptCallback(handle *libmemif.MemifPacketHandle, interruptCh <-chan struct{}, callback func(handle *libmemif.MemifPacketHandle)) {
for {
select {
case <-interruptCh:
callback(handle)
case <-stopCh:
handle.Close()
return
}
}
} | [
"func",
"CreateInterruptCallback",
"(",
"handle",
"*",
"libmemif",
".",
"MemifPacketHandle",
",",
"interruptCh",
"<-",
"chan",
"struct",
"{",
"}",
",",
"callback",
"func",
"(",
"handle",
"*",
"libmemif",
".",
"MemifPacketHandle",
")",
")",
"{",
"for",
"{",
"... | // Creates user-friendly memif interrupt callback | [
"Creates",
"user",
"-",
"friendly",
"memif",
"interrupt",
"callback"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/extras/libmemif/examples/gopacket/gopacket.go#L143-L153 |
12,678 | FDio/govpp | core/connection.go | Connect | func Connect(binapi adapter.VppAPI) (*Connection, error) {
// create new connection handle
c := newConnection(binapi, DefaultMaxReconnectAttempts, DefaultReconnectInterval)
// blocking attempt to connect to VPP
if err := c.connectVPP(); err != nil {
return nil, err
}
return c, nil
} | go | func Connect(binapi adapter.VppAPI) (*Connection, error) {
// create new connection handle
c := newConnection(binapi, DefaultMaxReconnectAttempts, DefaultReconnectInterval)
// blocking attempt to connect to VPP
if err := c.connectVPP(); err != nil {
return nil, err
}
return c, nil
} | [
"func",
"Connect",
"(",
"binapi",
"adapter",
".",
"VppAPI",
")",
"(",
"*",
"Connection",
",",
"error",
")",
"{",
"// create new connection handle",
"c",
":=",
"newConnection",
"(",
"binapi",
",",
"DefaultMaxReconnectAttempts",
",",
"DefaultReconnectInterval",
")",
... | // Connect connects to VPP API using specified adapter and returns a connection handle.
// This call blocks until it is either connected, or an error occurs.
// Only one connection attempt will be performed. | [
"Connect",
"connects",
"to",
"VPP",
"API",
"using",
"specified",
"adapter",
"and",
"returns",
"a",
"connection",
"handle",
".",
"This",
"call",
"blocks",
"until",
"it",
"is",
"either",
"connected",
"or",
"an",
"error",
"occurs",
".",
"Only",
"one",
"connecti... | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L142-L152 |
12,679 | FDio/govpp | core/connection.go | connectVPP | func (c *Connection) connectVPP() error {
log.Debug("Connecting to VPP..")
// blocking connect
if err := c.vppClient.Connect(); err != nil {
return err
}
log.Debugf("Connected to VPP.")
if err := c.retrieveMessageIDs(); err != nil {
c.vppClient.Disconnect()
return fmt.Errorf("VPP is incompatible: %v", err)
}
// store connected state
atomic.StoreUint32(&c.vppConnected, 1)
return nil
} | go | func (c *Connection) connectVPP() error {
log.Debug("Connecting to VPP..")
// blocking connect
if err := c.vppClient.Connect(); err != nil {
return err
}
log.Debugf("Connected to VPP.")
if err := c.retrieveMessageIDs(); err != nil {
c.vppClient.Disconnect()
return fmt.Errorf("VPP is incompatible: %v", err)
}
// store connected state
atomic.StoreUint32(&c.vppConnected, 1)
return nil
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"connectVPP",
"(",
")",
"error",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"// blocking connect",
"if",
"err",
":=",
"c",
".",
"vppClient",
".",
"Connect",
"(",
")",
";",
"err",
"!=",
"nil",
"... | // connectVPP performs blocking attempt to connect to VPP. | [
"connectVPP",
"performs",
"blocking",
"attempt",
"to",
"connect",
"to",
"VPP",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L170-L189 |
12,680 | FDio/govpp | core/connection.go | Disconnect | func (c *Connection) Disconnect() {
if c == nil {
return
}
if c.vppClient != nil {
c.disconnectVPP()
}
} | go | func (c *Connection) Disconnect() {
if c == nil {
return
}
if c.vppClient != nil {
c.disconnectVPP()
}
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"Disconnect",
"(",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"vppClient",
"!=",
"nil",
"{",
"c",
".",
"disconnectVPP",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Disconnect disconnects from VPP API and releases all connection-related resources. | [
"Disconnect",
"disconnects",
"from",
"VPP",
"API",
"and",
"releases",
"all",
"connection",
"-",
"related",
"resources",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L192-L200 |
12,681 | FDio/govpp | core/connection.go | disconnectVPP | func (c *Connection) disconnectVPP() {
if atomic.CompareAndSwapUint32(&c.vppConnected, 1, 0) {
c.vppClient.Disconnect()
}
} | go | func (c *Connection) disconnectVPP() {
if atomic.CompareAndSwapUint32(&c.vppConnected, 1, 0) {
c.vppClient.Disconnect()
}
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"disconnectVPP",
"(",
")",
"{",
"if",
"atomic",
".",
"CompareAndSwapUint32",
"(",
"&",
"c",
".",
"vppConnected",
",",
"1",
",",
"0",
")",
"{",
"c",
".",
"vppClient",
".",
"Disconnect",
"(",
")",
"\n",
"}",
... | // disconnectVPP disconnects from VPP in case it is connected. | [
"disconnectVPP",
"disconnects",
"from",
"VPP",
"in",
"case",
"it",
"is",
"connected",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L203-L207 |
12,682 | FDio/govpp | core/connection.go | newAPIChannel | func (c *Connection) newAPIChannel(reqChanBufSize, replyChanBufSize int) (*Channel, error) {
if c == nil {
return nil, errors.New("nil connection passed in")
}
// create new channel
chID := uint16(atomic.AddUint32(&c.maxChannelID, 1) & 0x7fff)
channel := newChannel(chID, c, c.codec, c, reqChanBufSize, replyChanBufSize)
// store API channel within the client
c.channelsLock.Lock()
c.channels[chID] = channel
c.channelsLock.Unlock()
// start watching on the request channel
go c.watchRequests(channel)
return channel, nil
} | go | func (c *Connection) newAPIChannel(reqChanBufSize, replyChanBufSize int) (*Channel, error) {
if c == nil {
return nil, errors.New("nil connection passed in")
}
// create new channel
chID := uint16(atomic.AddUint32(&c.maxChannelID, 1) & 0x7fff)
channel := newChannel(chID, c, c.codec, c, reqChanBufSize, replyChanBufSize)
// store API channel within the client
c.channelsLock.Lock()
c.channels[chID] = channel
c.channelsLock.Unlock()
// start watching on the request channel
go c.watchRequests(channel)
return channel, nil
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"newAPIChannel",
"(",
"reqChanBufSize",
",",
"replyChanBufSize",
"int",
")",
"(",
"*",
"Channel",
",",
"error",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\... | // NewAPIChannelBuffered returns a new API channel for communication with VPP via govpp core.
// It allows to specify custom buffer sizes for the request and reply Go channels. | [
"NewAPIChannelBuffered",
"returns",
"a",
"new",
"API",
"channel",
"for",
"communication",
"with",
"VPP",
"via",
"govpp",
"core",
".",
"It",
"allows",
"to",
"specify",
"custom",
"buffer",
"sizes",
"for",
"the",
"request",
"and",
"reply",
"Go",
"channels",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L219-L237 |
12,683 | FDio/govpp | core/connection.go | releaseAPIChannel | func (c *Connection) releaseAPIChannel(ch *Channel) {
log.WithFields(logger.Fields{
"channel": ch.id,
}).Debug("API channel released")
// delete the channel from channels map
c.channelsLock.Lock()
delete(c.channels, ch.id)
c.channelsLock.Unlock()
} | go | func (c *Connection) releaseAPIChannel(ch *Channel) {
log.WithFields(logger.Fields{
"channel": ch.id,
}).Debug("API channel released")
// delete the channel from channels map
c.channelsLock.Lock()
delete(c.channels, ch.id)
c.channelsLock.Unlock()
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"releaseAPIChannel",
"(",
"ch",
"*",
"Channel",
")",
"{",
"log",
".",
"WithFields",
"(",
"logger",
".",
"Fields",
"{",
"\"",
"\"",
":",
"ch",
".",
"id",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
... | // releaseAPIChannel releases API channel that needs to be closed. | [
"releaseAPIChannel",
"releases",
"API",
"channel",
"that",
"needs",
"to",
"be",
"closed",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L240-L249 |
12,684 | FDio/govpp | core/connection.go | connectLoop | func (c *Connection) connectLoop(connChan chan ConnectionEvent) {
reconnectAttempts := 0
// loop until connected
for {
if err := c.vppClient.WaitReady(); err != nil {
log.Warnf("wait ready failed: %v", err)
}
if err := c.connectVPP(); err == nil {
// signal connected event
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Connected}
break
} else if reconnectAttempts < c.maxAttempts {
reconnectAttempts++
log.Errorf("connecting failed (attempt %d/%d): %v", reconnectAttempts, c.maxAttempts, err)
time.Sleep(c.recInterval)
} else {
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Failed, Error: err}
return
}
}
// we are now connected, continue with health check loop
c.healthCheckLoop(connChan)
} | go | func (c *Connection) connectLoop(connChan chan ConnectionEvent) {
reconnectAttempts := 0
// loop until connected
for {
if err := c.vppClient.WaitReady(); err != nil {
log.Warnf("wait ready failed: %v", err)
}
if err := c.connectVPP(); err == nil {
// signal connected event
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Connected}
break
} else if reconnectAttempts < c.maxAttempts {
reconnectAttempts++
log.Errorf("connecting failed (attempt %d/%d): %v", reconnectAttempts, c.maxAttempts, err)
time.Sleep(c.recInterval)
} else {
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Failed, Error: err}
return
}
}
// we are now connected, continue with health check loop
c.healthCheckLoop(connChan)
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"connectLoop",
"(",
"connChan",
"chan",
"ConnectionEvent",
")",
"{",
"reconnectAttempts",
":=",
"0",
"\n\n",
"// loop until connected",
"for",
"{",
"if",
"err",
":=",
"c",
".",
"vppClient",
".",
"WaitReady",
"(",
")"... | // connectLoop attempts to connect to VPP until it succeeds.
// Then it continues with healthCheckLoop. | [
"connectLoop",
"attempts",
"to",
"connect",
"to",
"VPP",
"until",
"it",
"succeeds",
".",
"Then",
"it",
"continues",
"with",
"healthCheckLoop",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L253-L277 |
12,685 | FDio/govpp | core/connection.go | healthCheckLoop | func (c *Connection) healthCheckLoop(connChan chan ConnectionEvent) {
// create a separate API channel for health check probes
ch, err := c.newAPIChannel(1, 1)
if err != nil {
log.Error("Failed to create health check API channel, health check will be disabled:", err)
return
}
var (
sinceLastReply time.Duration
failedChecks int
)
// send health check probes until an error or timeout occurs
for {
// sleep until next health check probe period
time.Sleep(HealthCheckProbeInterval)
if atomic.LoadUint32(&c.vppConnected) == 0 {
// Disconnect has been called in the meantime, return the healthcheck - reconnect loop
log.Debug("Disconnected on request, exiting health check loop.")
return
}
// try draining probe replies from previous request before sending next one
select {
case <-ch.replyChan:
log.Debug("drained old probe reply from reply channel")
default:
}
// send the control ping request
ch.reqChan <- &vppRequest{msg: msgControlPing}
for {
// expect response within timeout period
select {
case vppReply := <-ch.replyChan:
err = vppReply.err
case <-time.After(HealthCheckReplyTimeout):
err = ErrProbeTimeout
// check if time since last reply from any other
// channel is less than health check reply timeout
c.lastReplyLock.Lock()
sinceLastReply = time.Since(c.lastReply)
c.lastReplyLock.Unlock()
if sinceLastReply < HealthCheckReplyTimeout {
log.Warnf("VPP health check probe timing out, but some request on other channel was received %v ago, continue waiting!", sinceLastReply)
continue
}
}
break
}
if err == ErrProbeTimeout {
failedChecks++
log.Warnf("VPP health check probe timed out after %v (%d. timeout)", HealthCheckReplyTimeout, failedChecks)
if failedChecks > HealthCheckThreshold {
// in case of exceeded failed check treshold, assume VPP disconnected
log.Errorf("VPP health check exceeded treshold for timeouts (>%d), assuming disconnect", HealthCheckThreshold)
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Disconnected}
break
}
} else if err != nil {
// in case of error, assume VPP disconnected
log.Errorf("VPP health check probe failed: %v", err)
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Disconnected, Error: err}
break
} else if failedChecks > 0 {
// in case of success after failed checks, clear failed check counter
failedChecks = 0
log.Infof("VPP health check probe OK")
}
}
// cleanup
ch.Close()
c.disconnectVPP()
// we are now disconnected, start connect loop
c.connectLoop(connChan)
} | go | func (c *Connection) healthCheckLoop(connChan chan ConnectionEvent) {
// create a separate API channel for health check probes
ch, err := c.newAPIChannel(1, 1)
if err != nil {
log.Error("Failed to create health check API channel, health check will be disabled:", err)
return
}
var (
sinceLastReply time.Duration
failedChecks int
)
// send health check probes until an error or timeout occurs
for {
// sleep until next health check probe period
time.Sleep(HealthCheckProbeInterval)
if atomic.LoadUint32(&c.vppConnected) == 0 {
// Disconnect has been called in the meantime, return the healthcheck - reconnect loop
log.Debug("Disconnected on request, exiting health check loop.")
return
}
// try draining probe replies from previous request before sending next one
select {
case <-ch.replyChan:
log.Debug("drained old probe reply from reply channel")
default:
}
// send the control ping request
ch.reqChan <- &vppRequest{msg: msgControlPing}
for {
// expect response within timeout period
select {
case vppReply := <-ch.replyChan:
err = vppReply.err
case <-time.After(HealthCheckReplyTimeout):
err = ErrProbeTimeout
// check if time since last reply from any other
// channel is less than health check reply timeout
c.lastReplyLock.Lock()
sinceLastReply = time.Since(c.lastReply)
c.lastReplyLock.Unlock()
if sinceLastReply < HealthCheckReplyTimeout {
log.Warnf("VPP health check probe timing out, but some request on other channel was received %v ago, continue waiting!", sinceLastReply)
continue
}
}
break
}
if err == ErrProbeTimeout {
failedChecks++
log.Warnf("VPP health check probe timed out after %v (%d. timeout)", HealthCheckReplyTimeout, failedChecks)
if failedChecks > HealthCheckThreshold {
// in case of exceeded failed check treshold, assume VPP disconnected
log.Errorf("VPP health check exceeded treshold for timeouts (>%d), assuming disconnect", HealthCheckThreshold)
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Disconnected}
break
}
} else if err != nil {
// in case of error, assume VPP disconnected
log.Errorf("VPP health check probe failed: %v", err)
connChan <- ConnectionEvent{Timestamp: time.Now(), State: Disconnected, Error: err}
break
} else if failedChecks > 0 {
// in case of success after failed checks, clear failed check counter
failedChecks = 0
log.Infof("VPP health check probe OK")
}
}
// cleanup
ch.Close()
c.disconnectVPP()
// we are now disconnected, start connect loop
c.connectLoop(connChan)
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"healthCheckLoop",
"(",
"connChan",
"chan",
"ConnectionEvent",
")",
"{",
"// create a separate API channel for health check probes",
"ch",
",",
"err",
":=",
"c",
".",
"newAPIChannel",
"(",
"1",
",",
"1",
")",
"\n",
"if",... | // healthCheckLoop checks whether connection to VPP is alive. In case of disconnect,
// it continues with connectLoop and tries to reconnect. | [
"healthCheckLoop",
"checks",
"whether",
"connection",
"to",
"VPP",
"is",
"alive",
".",
"In",
"case",
"of",
"disconnect",
"it",
"continues",
"with",
"connectLoop",
"and",
"tries",
"to",
"reconnect",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L281-L365 |
12,686 | FDio/govpp | core/connection.go | GetMessageID | func (c *Connection) GetMessageID(msg api.Message) (uint16, error) {
if c == nil {
return 0, errors.New("nil connection passed in")
}
if msgID, ok := c.msgIDs[getMsgNameWithCrc(msg)]; ok {
return msgID, nil
}
msgID, err := c.vppClient.GetMsgID(msg.GetMessageName(), msg.GetCrcString())
if err != nil {
return 0, err
}
c.msgIDs[getMsgNameWithCrc(msg)] = msgID
c.msgMap[msgID] = msg
return msgID, nil
} | go | func (c *Connection) GetMessageID(msg api.Message) (uint16, error) {
if c == nil {
return 0, errors.New("nil connection passed in")
}
if msgID, ok := c.msgIDs[getMsgNameWithCrc(msg)]; ok {
return msgID, nil
}
msgID, err := c.vppClient.GetMsgID(msg.GetMessageName(), msg.GetCrcString())
if err != nil {
return 0, err
}
c.msgIDs[getMsgNameWithCrc(msg)] = msgID
c.msgMap[msgID] = msg
return msgID, nil
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"GetMessageID",
"(",
"msg",
"api",
".",
"Message",
")",
"(",
"uint16",
",",
"error",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n... | // GetMessageID returns message identifier of given API message. | [
"GetMessageID",
"returns",
"message",
"identifier",
"of",
"given",
"API",
"message",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L378-L396 |
12,687 | FDio/govpp | core/connection.go | LookupByID | func (c *Connection) LookupByID(msgID uint16) (api.Message, error) {
if c == nil {
return nil, errors.New("nil connection passed in")
}
if msg, ok := c.msgMap[msgID]; ok {
return msg, nil
}
return nil, fmt.Errorf("unknown message ID: %d", msgID)
} | go | func (c *Connection) LookupByID(msgID uint16) (api.Message, error) {
if c == nil {
return nil, errors.New("nil connection passed in")
}
if msg, ok := c.msgMap[msgID]; ok {
return msg, nil
}
return nil, fmt.Errorf("unknown message ID: %d", msgID)
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"LookupByID",
"(",
"msgID",
"uint16",
")",
"(",
"api",
".",
"Message",
",",
"error",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"... | // LookupByID looks up message name and crc by ID. | [
"LookupByID",
"looks",
"up",
"message",
"name",
"and",
"crc",
"by",
"ID",
"."
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L399-L409 |
12,688 | FDio/govpp | core/connection.go | retrieveMessageIDs | func (c *Connection) retrieveMessageIDs() (err error) {
t := time.Now()
msgs := api.GetRegisteredMessages()
var n int
for name, msg := range msgs {
msgID, err := c.GetMessageID(msg)
if err != nil {
log.Debugf("retrieving msgID for %s failed: %v", name, err)
continue
}
n++
if c.pingReqID == 0 && msg.GetMessageName() == msgControlPing.GetMessageName() {
c.pingReqID = msgID
msgControlPing = reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
} else if c.pingReplyID == 0 && msg.GetMessageName() == msgControlPingReply.GetMessageName() {
c.pingReplyID = msgID
msgControlPingReply = reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
}
if debugMsgIDs {
log.Debugf("message %q (%s) has ID: %d", name, getMsgNameWithCrc(msg), msgID)
}
}
log.Debugf("retrieved %d/%d msgIDs (took %s)", n, len(msgs), time.Since(t))
return nil
} | go | func (c *Connection) retrieveMessageIDs() (err error) {
t := time.Now()
msgs := api.GetRegisteredMessages()
var n int
for name, msg := range msgs {
msgID, err := c.GetMessageID(msg)
if err != nil {
log.Debugf("retrieving msgID for %s failed: %v", name, err)
continue
}
n++
if c.pingReqID == 0 && msg.GetMessageName() == msgControlPing.GetMessageName() {
c.pingReqID = msgID
msgControlPing = reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
} else if c.pingReplyID == 0 && msg.GetMessageName() == msgControlPingReply.GetMessageName() {
c.pingReplyID = msgID
msgControlPingReply = reflect.New(reflect.TypeOf(msg).Elem()).Interface().(api.Message)
}
if debugMsgIDs {
log.Debugf("message %q (%s) has ID: %d", name, getMsgNameWithCrc(msg), msgID)
}
}
log.Debugf("retrieved %d/%d msgIDs (took %s)", n, len(msgs), time.Since(t))
return nil
} | [
"func",
"(",
"c",
"*",
"Connection",
")",
"retrieveMessageIDs",
"(",
")",
"(",
"err",
"error",
")",
"{",
"t",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"msgs",
":=",
"api",
".",
"GetRegisteredMessages",
"(",
")",
"\n\n",
"var",
"n",
"int",
"\n",
... | // retrieveMessageIDs retrieves IDs for all registered messages and stores them in map | [
"retrieveMessageIDs",
"retrieves",
"IDs",
"for",
"all",
"registered",
"messages",
"and",
"stores",
"them",
"in",
"map"
] | f614a0af720702c8db959b6641b4faea5f98c339 | https://github.com/FDio/govpp/blob/f614a0af720702c8db959b6641b4faea5f98c339/core/connection.go#L412-L441 |
12,689 | mailgun/lemma | httpsign/nonce.go | NewNonceCache | func NewNonceCache(capacity int, cacheTTL int, timeProvider timetools.TimeProvider) (*NonceCache, error) {
c, err := ttlmap.NewMapWithProvider(capacity, timeProvider)
if err != nil {
return nil, err
}
return &NonceCache{
cache: c,
cacheTTL: cacheTTL,
timeProvider: timeProvider,
}, nil
} | go | func NewNonceCache(capacity int, cacheTTL int, timeProvider timetools.TimeProvider) (*NonceCache, error) {
c, err := ttlmap.NewMapWithProvider(capacity, timeProvider)
if err != nil {
return nil, err
}
return &NonceCache{
cache: c,
cacheTTL: cacheTTL,
timeProvider: timeProvider,
}, nil
} | [
"func",
"NewNonceCache",
"(",
"capacity",
"int",
",",
"cacheTTL",
"int",
",",
"timeProvider",
"timetools",
".",
"TimeProvider",
")",
"(",
"*",
"NonceCache",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"ttlmap",
".",
"NewMapWithProvider",
"(",
"capacity",
... | // Return a new NonceCache. Allows you to control cache capacity, ttl, as well as the TimeProvider. | [
"Return",
"a",
"new",
"NonceCache",
".",
"Allows",
"you",
"to",
"control",
"cache",
"capacity",
"ttl",
"as",
"well",
"as",
"the",
"TimeProvider",
"."
] | 4214099fb348c416514bc2c93087fde56216d7b5 | https://github.com/mailgun/lemma/blob/4214099fb348c416514bc2c93087fde56216d7b5/httpsign/nonce.go#L18-L29 |
12,690 | mailgun/lemma | httpsign/auth.go | NewWithProviders | func NewWithProviders(config *Config, timeProvider timetools.TimeProvider,
randomProvider random.RandomProvider) (*Service, error) {
// config is required!
if config == nil {
return nil, fmt.Errorf("config is required.")
}
// set defaults if not set
if config.NonceCacheCapacity < 1 {
config.NonceCacheCapacity = CacheCapacity
}
if config.NonceCacheTimeout < 1 {
config.NonceCacheTimeout = CacheTimeout
}
if config.NonceHeaderName == "" {
config.NonceHeaderName = XMailgunNonce
}
if config.TimestampHeaderName == "" {
config.TimestampHeaderName = XMailgunTimestamp
}
if config.SignatureHeaderName == "" {
config.SignatureHeaderName = XMailgunSignature
}
if config.SignatureVersionHeaderName == "" {
config.SignatureVersionHeaderName = XMailgunSignatureVersion
}
// setup metrics service
metricsClient := metrics.NewNop()
if config.EmitStats {
// get hostname of box
hostname, err := os.Hostname()
if err != nil {
return nil, fmt.Errorf("failed to obtain hostname: %v", err)
}
// build lemma prefix
prefix := "lemma." + strings.Replace(hostname, ".", "_", -1)
if config.StatsdPrefix != "" {
prefix += "." + config.StatsdPrefix
}
// build metrics client
hostport := fmt.Sprintf("%v:%v", config.StatsdHost, config.StatsdPort)
metricsClient, err = metrics.NewWithOptions(hostport, prefix, metrics.Options{UseBuffering: true})
if err != nil {
return nil, err
}
}
// Read in key from KeyPath or if not given, try getting them from KeyBytes.
var keyBytes []byte
var err error
if config.KeyPath != "" {
if keyBytes, err = readKeyFromDisk(config.KeyPath); err != nil {
return nil, err
}
} else {
if config.KeyBytes == nil {
return nil, errors.New("no key bytes provided")
}
keyBytes = config.KeyBytes
}
// setup nonce cache
ncache, err := NewNonceCache(config.NonceCacheCapacity, config.NonceCacheTimeout, timeProvider)
if err != nil {
return nil, err
}
// return service
return &Service{
config: config,
nonceCache: ncache,
secretKey: keyBytes,
timeProvider: timeProvider,
randomProvider: randomProvider,
metricsClient: metricsClient,
}, nil
} | go | func NewWithProviders(config *Config, timeProvider timetools.TimeProvider,
randomProvider random.RandomProvider) (*Service, error) {
// config is required!
if config == nil {
return nil, fmt.Errorf("config is required.")
}
// set defaults if not set
if config.NonceCacheCapacity < 1 {
config.NonceCacheCapacity = CacheCapacity
}
if config.NonceCacheTimeout < 1 {
config.NonceCacheTimeout = CacheTimeout
}
if config.NonceHeaderName == "" {
config.NonceHeaderName = XMailgunNonce
}
if config.TimestampHeaderName == "" {
config.TimestampHeaderName = XMailgunTimestamp
}
if config.SignatureHeaderName == "" {
config.SignatureHeaderName = XMailgunSignature
}
if config.SignatureVersionHeaderName == "" {
config.SignatureVersionHeaderName = XMailgunSignatureVersion
}
// setup metrics service
metricsClient := metrics.NewNop()
if config.EmitStats {
// get hostname of box
hostname, err := os.Hostname()
if err != nil {
return nil, fmt.Errorf("failed to obtain hostname: %v", err)
}
// build lemma prefix
prefix := "lemma." + strings.Replace(hostname, ".", "_", -1)
if config.StatsdPrefix != "" {
prefix += "." + config.StatsdPrefix
}
// build metrics client
hostport := fmt.Sprintf("%v:%v", config.StatsdHost, config.StatsdPort)
metricsClient, err = metrics.NewWithOptions(hostport, prefix, metrics.Options{UseBuffering: true})
if err != nil {
return nil, err
}
}
// Read in key from KeyPath or if not given, try getting them from KeyBytes.
var keyBytes []byte
var err error
if config.KeyPath != "" {
if keyBytes, err = readKeyFromDisk(config.KeyPath); err != nil {
return nil, err
}
} else {
if config.KeyBytes == nil {
return nil, errors.New("no key bytes provided")
}
keyBytes = config.KeyBytes
}
// setup nonce cache
ncache, err := NewNonceCache(config.NonceCacheCapacity, config.NonceCacheTimeout, timeProvider)
if err != nil {
return nil, err
}
// return service
return &Service{
config: config,
nonceCache: ncache,
secretKey: keyBytes,
timeProvider: timeProvider,
randomProvider: randomProvider,
metricsClient: metricsClient,
}, nil
} | [
"func",
"NewWithProviders",
"(",
"config",
"*",
"Config",
",",
"timeProvider",
"timetools",
".",
"TimeProvider",
",",
"randomProvider",
"random",
".",
"RandomProvider",
")",
"(",
"*",
"Service",
",",
"error",
")",
"{",
"// config is required!",
"if",
"config",
"... | // Returns a new Service. Provides control over time and random providers. | [
"Returns",
"a",
"new",
"Service",
".",
"Provides",
"control",
"over",
"time",
"and",
"random",
"providers",
"."
] | 4214099fb348c416514bc2c93087fde56216d7b5 | https://github.com/mailgun/lemma/blob/4214099fb348c416514bc2c93087fde56216d7b5/httpsign/auth.go#L77-L157 |
12,691 | mailgun/lemma | httpsign/auth.go | SignRequestWithKey | func (s *Service) SignRequestWithKey(r *http.Request, secretKey []byte) error {
// extract request body bytes
bodyBytes, err := readBody(r)
if err != nil {
return err
}
// extract any headers if requested
headerValues, err := extractHeaderValues(r, s.config.HeadersToSign)
if err != nil {
return err
}
// get 128-bit random number from /dev/urandom and base16 encode it
nonce, err := s.randomProvider.HexDigest(16)
if err != nil {
return fmt.Errorf("unable to get random : %v", err)
}
// get current timestamp
timestamp := strconv.FormatInt(s.timeProvider.UtcNow().Unix(), 10)
// compute the hmac and base16 encode it
computedMAC := computeMAC(secretKey, s.config.SignVerbAndURI, r.Method, r.URL.RequestURI(),
timestamp, nonce, bodyBytes, headerValues)
signature := hex.EncodeToString(computedMAC)
// set headers
r.Header.Set(s.config.NonceHeaderName, nonce)
r.Header.Set(s.config.TimestampHeaderName, timestamp)
r.Header.Set(s.config.SignatureHeaderName, signature)
r.Header.Set(s.config.SignatureVersionHeaderName, "2")
// set the body bytes we read in to nil to hint to the gc to pick it up
bodyBytes = nil
return nil
} | go | func (s *Service) SignRequestWithKey(r *http.Request, secretKey []byte) error {
// extract request body bytes
bodyBytes, err := readBody(r)
if err != nil {
return err
}
// extract any headers if requested
headerValues, err := extractHeaderValues(r, s.config.HeadersToSign)
if err != nil {
return err
}
// get 128-bit random number from /dev/urandom and base16 encode it
nonce, err := s.randomProvider.HexDigest(16)
if err != nil {
return fmt.Errorf("unable to get random : %v", err)
}
// get current timestamp
timestamp := strconv.FormatInt(s.timeProvider.UtcNow().Unix(), 10)
// compute the hmac and base16 encode it
computedMAC := computeMAC(secretKey, s.config.SignVerbAndURI, r.Method, r.URL.RequestURI(),
timestamp, nonce, bodyBytes, headerValues)
signature := hex.EncodeToString(computedMAC)
// set headers
r.Header.Set(s.config.NonceHeaderName, nonce)
r.Header.Set(s.config.TimestampHeaderName, timestamp)
r.Header.Set(s.config.SignatureHeaderName, signature)
r.Header.Set(s.config.SignatureVersionHeaderName, "2")
// set the body bytes we read in to nil to hint to the gc to pick it up
bodyBytes = nil
return nil
} | [
"func",
"(",
"s",
"*",
"Service",
")",
"SignRequestWithKey",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"secretKey",
"[",
"]",
"byte",
")",
"error",
"{",
"// extract request body bytes",
"bodyBytes",
",",
"err",
":=",
"readBody",
"(",
"r",
")",
"\n",
"i... | // Signs a given HTTP request with signature, nonce, and timestamp. Signs the
// message with the passed in key not the one initialized with. | [
"Signs",
"a",
"given",
"HTTP",
"request",
"with",
"signature",
"nonce",
"and",
"timestamp",
".",
"Signs",
"the",
"message",
"with",
"the",
"passed",
"in",
"key",
"not",
"the",
"one",
"initialized",
"with",
"."
] | 4214099fb348c416514bc2c93087fde56216d7b5 | https://github.com/mailgun/lemma/blob/4214099fb348c416514bc2c93087fde56216d7b5/httpsign/auth.go#L169-L206 |
12,692 | mailgun/lemma | secret/key.go | NewKey | func NewKey() (*[SecretKeyLength]byte, error) {
// get 32-bytes of random from /dev/urandom
bytes, err := randomProvider.Bytes(SecretKeyLength)
if err != nil {
return nil, fmt.Errorf("unable to generate random: %v", err)
}
return KeySliceToArray(bytes)
} | go | func NewKey() (*[SecretKeyLength]byte, error) {
// get 32-bytes of random from /dev/urandom
bytes, err := randomProvider.Bytes(SecretKeyLength)
if err != nil {
return nil, fmt.Errorf("unable to generate random: %v", err)
}
return KeySliceToArray(bytes)
} | [
"func",
"NewKey",
"(",
")",
"(",
"*",
"[",
"SecretKeyLength",
"]",
"byte",
",",
"error",
")",
"{",
"// get 32-bytes of random from /dev/urandom",
"bytes",
",",
"err",
":=",
"randomProvider",
".",
"Bytes",
"(",
"SecretKeyLength",
")",
"\n",
"if",
"err",
"!=",
... | // NewKey returns a new key that can be used to encrypt and decrypt messages. | [
"NewKey",
"returns",
"a",
"new",
"key",
"that",
"can",
"be",
"used",
"to",
"encrypt",
"and",
"decrypt",
"messages",
"."
] | 4214099fb348c416514bc2c93087fde56216d7b5 | https://github.com/mailgun/lemma/blob/4214099fb348c416514bc2c93087fde56216d7b5/secret/key.go#L10-L18 |
12,693 | xiam/exif | exif.go | Read | func Read(file string) (*Data, error) {
data := New()
if err := data.Open(file); err != nil {
return nil, err
}
return data, nil
} | go | func Read(file string) (*Data, error) {
data := New()
if err := data.Open(file); err != nil {
return nil, err
}
return data, nil
} | [
"func",
"Read",
"(",
"file",
"string",
")",
"(",
"*",
"Data",
",",
"error",
")",
"{",
"data",
":=",
"New",
"(",
")",
"\n",
"if",
"err",
":=",
"data",
".",
"Open",
"(",
"file",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\... | // Read attempts to read EXIF data from a file. | [
"Read",
"attempts",
"to",
"read",
"EXIF",
"data",
"from",
"a",
"file",
"."
] | 33e82e3db72f03c4d55d10b7275d267fc7cd0e45 | https://github.com/xiam/exif/blob/33e82e3db72f03c4d55d10b7275d267fc7cd0e45/exif.go#L66-L72 |
12,694 | xiam/exif | exif.go | Open | func (d *Data) Open(file string) error {
cfile := C.CString(file)
defer C.free(unsafe.Pointer(cfile))
exifData := C.exif_data_new_from_file(cfile)
if exifData == nil {
return ErrNoExifData
}
defer C.exif_data_unref(exifData)
return d.parseExifData(exifData)
} | go | func (d *Data) Open(file string) error {
cfile := C.CString(file)
defer C.free(unsafe.Pointer(cfile))
exifData := C.exif_data_new_from_file(cfile)
if exifData == nil {
return ErrNoExifData
}
defer C.exif_data_unref(exifData)
return d.parseExifData(exifData)
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"Open",
"(",
"file",
"string",
")",
"error",
"{",
"cfile",
":=",
"C",
".",
"CString",
"(",
"file",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cfile",
")",
")",
"\n\n",
"exifData"... | // Open opens a file path and loads its EXIF data. | [
"Open",
"opens",
"a",
"file",
"path",
"and",
"loads",
"its",
"EXIF",
"data",
"."
] | 33e82e3db72f03c4d55d10b7275d267fc7cd0e45 | https://github.com/xiam/exif/blob/33e82e3db72f03c4d55d10b7275d267fc7cd0e45/exif.go#L75-L88 |
12,695 | xiam/exif | exif.go | Write | func (d *Data) Write(p []byte) (n int, err error) {
if d.exifLoader == nil {
d.exifLoader = C.exif_loader_new()
runtime.SetFinalizer(d, (*Data).cleanup)
}
res := C.exif_loader_write(d.exifLoader, (*C.uchar)(unsafe.Pointer(&p[0])), C.uint(len(p)))
if res == 1 {
return len(p), nil
}
return len(p), ErrFoundExifInData
} | go | func (d *Data) Write(p []byte) (n int, err error) {
if d.exifLoader == nil {
d.exifLoader = C.exif_loader_new()
runtime.SetFinalizer(d, (*Data).cleanup)
}
res := C.exif_loader_write(d.exifLoader, (*C.uchar)(unsafe.Pointer(&p[0])), C.uint(len(p)))
if res == 1 {
return len(p), nil
}
return len(p), ErrFoundExifInData
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"if",
"d",
".",
"exifLoader",
"==",
"nil",
"{",
"d",
".",
"exifLoader",
"=",
"C",
".",
"exif_loader_new",
"(",
")",
... | // Write writes bytes to the exif loader. Sends ErrFoundExifInData error when
// enough bytes have been sent. | [
"Write",
"writes",
"bytes",
"to",
"the",
"exif",
"loader",
".",
"Sends",
"ErrFoundExifInData",
"error",
"when",
"enough",
"bytes",
"have",
"been",
"sent",
"."
] | 33e82e3db72f03c4d55d10b7275d267fc7cd0e45 | https://github.com/xiam/exif/blob/33e82e3db72f03c4d55d10b7275d267fc7cd0e45/exif.go#L109-L121 |
12,696 | xiam/exif | exif.go | Parse | func (d *Data) Parse() error {
defer d.cleanup()
exifData := C.exif_loader_get_data(d.exifLoader)
if exifData == nil {
return fmt.Errorf(ErrNoExifData.Error(), "")
}
defer func() {
C.exif_data_unref(exifData)
}()
return d.parseExifData(exifData)
} | go | func (d *Data) Parse() error {
defer d.cleanup()
exifData := C.exif_loader_get_data(d.exifLoader)
if exifData == nil {
return fmt.Errorf(ErrNoExifData.Error(), "")
}
defer func() {
C.exif_data_unref(exifData)
}()
return d.parseExifData(exifData)
} | [
"func",
"(",
"d",
"*",
"Data",
")",
"Parse",
"(",
")",
"error",
"{",
"defer",
"d",
".",
"cleanup",
"(",
")",
"\n\n",
"exifData",
":=",
"C",
".",
"exif_loader_get_data",
"(",
"d",
".",
"exifLoader",
")",
"\n",
"if",
"exifData",
"==",
"nil",
"{",
"re... | // Parse finalizes the data loader and sets the tags | [
"Parse",
"finalizes",
"the",
"data",
"loader",
"and",
"sets",
"the",
"tags"
] | 33e82e3db72f03c4d55d10b7275d267fc7cd0e45 | https://github.com/xiam/exif/blob/33e82e3db72f03c4d55d10b7275d267fc7cd0e45/exif.go#L124-L137 |
12,697 | tomcraven/goga | bitset.go | Create | func (b *Bitset) Create(size int) {
b.size = size
b.bits = make([]int, size)
} | go | func (b *Bitset) Create(size int) {
b.size = size
b.bits = make([]int, size)
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"Create",
"(",
"size",
"int",
")",
"{",
"b",
".",
"size",
"=",
"size",
"\n",
"b",
".",
"bits",
"=",
"make",
"(",
"[",
"]",
"int",
",",
"size",
")",
"\n",
"}"
] | // Create - creates a bitset of length 'size' | [
"Create",
"-",
"creates",
"a",
"bitset",
"of",
"length",
"size"
] | 3b7915ecdd7bb6616dc3ceed450068e092ed87bc | https://github.com/tomcraven/goga/blob/3b7915ecdd7bb6616dc3ceed450068e092ed87bc/bitset.go#L10-L13 |
12,698 | tomcraven/goga | bitset.go | Get | func (b *Bitset) Get(index int) int {
if index < b.size {
return b.bits[index]
}
return -1
} | go | func (b *Bitset) Get(index int) int {
if index < b.size {
return b.bits[index]
}
return -1
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"Get",
"(",
"index",
"int",
")",
"int",
"{",
"if",
"index",
"<",
"b",
".",
"size",
"{",
"return",
"b",
".",
"bits",
"[",
"index",
"]",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] | // Get returns the value in the bitset at index 'index'
// or -1 if the index is out of range | [
"Get",
"returns",
"the",
"value",
"in",
"the",
"bitset",
"at",
"index",
"index",
"or",
"-",
"1",
"if",
"the",
"index",
"is",
"out",
"of",
"range"
] | 3b7915ecdd7bb6616dc3ceed450068e092ed87bc | https://github.com/tomcraven/goga/blob/3b7915ecdd7bb6616dc3ceed450068e092ed87bc/bitset.go#L22-L27 |
12,699 | tomcraven/goga | bitset.go | Set | func (b *Bitset) Set(index, value int) bool {
if index < b.size {
b.setImpl(index, value)
return true
}
return false
} | go | func (b *Bitset) Set(index, value int) bool {
if index < b.size {
b.setImpl(index, value)
return true
}
return false
} | [
"func",
"(",
"b",
"*",
"Bitset",
")",
"Set",
"(",
"index",
",",
"value",
"int",
")",
"bool",
"{",
"if",
"index",
"<",
"b",
".",
"size",
"{",
"b",
".",
"setImpl",
"(",
"index",
",",
"value",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"return"... | // Set assigns value 'value' to the bit at index 'index' | [
"Set",
"assigns",
"value",
"value",
"to",
"the",
"bit",
"at",
"index",
"index"
] | 3b7915ecdd7bb6616dc3ceed450068e092ed87bc | https://github.com/tomcraven/goga/blob/3b7915ecdd7bb6616dc3ceed450068e092ed87bc/bitset.go#L39-L45 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.