2016-04-13 12:17:46 +00:00
|
|
|
package sysdig
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/csv"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
RX = iota
|
|
|
|
TX
|
|
|
|
)
|
|
|
|
|
|
|
|
type Record struct {
|
2016-05-09 15:33:33 +00:00
|
|
|
//Host, Container, Process string
|
|
|
|
//Pid, Tid uint64
|
|
|
|
Proto string
|
|
|
|
ServerIp net.IP
|
|
|
|
ServerPort uint16
|
|
|
|
ClientIp net.IP
|
|
|
|
ClientPort uint16
|
|
|
|
Direction int
|
|
|
|
Bytes uint64
|
2016-04-13 12:17:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func ParseOutput(result string) ([]Record, error) {
|
|
|
|
r := csv.NewReader(strings.NewReader(result))
|
|
|
|
r.Comma = '\t'
|
|
|
|
|
|
|
|
var records []Record
|
|
|
|
for {
|
|
|
|
record, err := r.Read()
|
|
|
|
if err == io.EOF {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2016-05-09 15:33:33 +00:00
|
|
|
sip := net.ParseIP(record[1])
|
2016-04-13 12:17:46 +00:00
|
|
|
if sip == nil {
|
2016-05-09 15:33:33 +00:00
|
|
|
return nil, fmt.Errorf("invalid ip '%s'", record[1])
|
2016-04-13 12:17:46 +00:00
|
|
|
}
|
2016-05-09 15:33:33 +00:00
|
|
|
sport, err := strconv.ParseUint(record[2], 10, 16)
|
2016-04-13 12:17:46 +00:00
|
|
|
if err != nil {
|
2016-05-09 15:33:33 +00:00
|
|
|
return nil, fmt.Errorf("invalid port %s: %v", record[2], err)
|
2016-04-13 12:17:46 +00:00
|
|
|
}
|
2016-05-09 15:33:33 +00:00
|
|
|
cip := net.ParseIP(record[3])
|
2016-04-13 12:17:46 +00:00
|
|
|
if cip == nil {
|
2016-05-09 15:33:33 +00:00
|
|
|
return nil, fmt.Errorf("invalid ip '%s'", record[3])
|
2016-04-13 12:17:46 +00:00
|
|
|
}
|
2016-05-09 15:33:33 +00:00
|
|
|
cport, err := strconv.ParseUint(record[4], 10, 16)
|
2016-04-13 12:17:46 +00:00
|
|
|
if err != nil {
|
2016-05-09 15:33:33 +00:00
|
|
|
return nil, fmt.Errorf("invalid port %s: %v", record[4], err)
|
2016-04-13 12:17:46 +00:00
|
|
|
}
|
|
|
|
var direction int
|
2016-05-09 15:33:33 +00:00
|
|
|
if record[5] == "rx" {
|
2016-04-13 12:17:46 +00:00
|
|
|
direction = RX
|
|
|
|
} else {
|
|
|
|
direction = TX
|
|
|
|
}
|
|
|
|
|
2016-05-09 15:33:33 +00:00
|
|
|
bytes, err := strconv.ParseUint(record[6], 10, 64)
|
2016-04-13 12:17:46 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid transmission size %s: %v", record[11], err)
|
|
|
|
}
|
|
|
|
records = append(records, Record{
|
|
|
|
record[0],
|
|
|
|
sip,
|
|
|
|
uint16(sport),
|
|
|
|
cip,
|
|
|
|
uint16(cport),
|
|
|
|
direction,
|
|
|
|
bytes,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return records, nil
|
|
|
|
}
|