coreos / go-iptables

Go wrapper around iptables utility
Apache License 2.0
1.12k stars 256 forks source link

Add Stats method to list rules w/ packets, bytes statistics #29

Closed phensley closed 7 years ago

phensley commented 7 years ago

This commit adds a Stats(table, chain string) method that parses the output of -L -v -n -x (verbose, numeric, exact).

My application allows an operator to add blocking rules to a given table, and periodically polls for packet and byte statistics to determine how much traffic hits each rule.

Here's an example of how I'm hooking this into the application. Hopefully some others will find it useful.

type Stat struct {
    Protocol  string
    Source    string
    Options   []string
    Packets   uint64
    Bytes     uint64
}

func parseStats(rows [][]string) ([]*Stat, error) {
    stats := []*Stat{}
    for _, row := range rows {
        pkts, err := strconv.ParseInt(row[0], 10, 64)
        if err != nil {
            return nil, fmt.Errorf("Error parsing 'pkts' field %#v: %s", row[0], err)
        }
        bytes, err := strconv.ParseInt(row[1], 10, 64)
        if err != nil {
            return nil, fmt.Errorf("Error parsing 'bytes' field: %#v: %s", row[1], err)
        }

        stat := &Stat{
            Protocol:  row[3],
            Source:    row[7],
            Options:   row[9:],
            Packets:   uint64(pkts),
            Bytes:     uint64(bytes),
        }
        stats = append(stats, stat)
    }
    return stats, nil
}
lucab commented 7 years ago

@squeed mind a review?

squeed commented 7 years ago

LGTM, would you mind rebasing?