|
| 1 | +/* |
| 2 | + * Copyright (C) 2022 IBM, Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + * |
| 16 | + */ |
| 17 | + |
| 18 | +package main |
| 19 | + |
| 20 | +import ( |
| 21 | + "flag" |
| 22 | + "log" |
| 23 | + "net" |
| 24 | + |
| 25 | + "github.com/netobserv/netobserv-ebpf-agent/pkg/grpc" |
| 26 | + "github.com/netobserv/netobserv-ebpf-agent/pkg/pbflow" |
| 27 | +) |
| 28 | + |
| 29 | +var ( |
| 30 | + port = flag.Int("listen_port", 9999, "TCP port to listen for flows") |
| 31 | +) |
| 32 | + |
| 33 | +var protocolByNumber = map[uint32]string{ |
| 34 | + 1: "icmp", |
| 35 | + 2: "igmp", |
| 36 | + 6: "tcp", |
| 37 | + 17: "udp", |
| 38 | + 58: "ipv6-icmp", |
| 39 | +} |
| 40 | + |
| 41 | +func ipIntToNetIP(ipAsInt uint32) net.IP { |
| 42 | + var bytes [4]byte |
| 43 | + bytes[0] = byte(ipAsInt & 0xFF) |
| 44 | + bytes[1] = byte((ipAsInt >> 8) & 0xFF) |
| 45 | + bytes[2] = byte((ipAsInt >> 16) & 0xFF) |
| 46 | + bytes[3] = byte((ipAsInt >> 24) & 0xFF) |
| 47 | + |
| 48 | + return net.IPv4(bytes[3], bytes[2], bytes[1], bytes[0]) |
| 49 | +} |
| 50 | + |
| 51 | +// tcpdump flow collector |
| 52 | +func main() { |
| 53 | + log.SetFlags(0) |
| 54 | + flag.Parse() |
| 55 | + |
| 56 | + receivedRecords := make(chan *pbflow.Records, 100) |
| 57 | + log.Println("starting flowlogs-dump-collector on port", *port) |
| 58 | + go func() { |
| 59 | + _, err := grpc.StartCollector(*port, receivedRecords) |
| 60 | + if err != nil { |
| 61 | + panic(err) |
| 62 | + } |
| 63 | + }() |
| 64 | + for records := range receivedRecords { |
| 65 | + for _, record := range records.Entries { |
| 66 | + log.Printf("%v %s IP %s:%d > %s:%d: protocol:%s dir:%d bytes:%d packets:%d ends: %v\n", |
| 67 | + record.TimeFlowStart.AsTime().Local().Format("15:04:05.000000"), |
| 68 | + record.Interface, |
| 69 | + ipIntToNetIP(record.Network.GetSrcAddr().GetIpv4()).String(), |
| 70 | + record.Transport.SrcPort, |
| 71 | + ipIntToNetIP(record.Network.GetDstAddr().GetIpv4()).String(), |
| 72 | + record.Transport.DstPort, |
| 73 | + protocolByNumber[record.Transport.Protocol], |
| 74 | + record.Direction, |
| 75 | + record.Bytes, |
| 76 | + record.Packets, |
| 77 | + record.TimeFlowEnd.AsTime().Local().Format("15:04:05.000000"), |
| 78 | + ) |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments