aboutsummaryrefslogtreecommitdiff
path: root/collector/conntrack_exec_linux.go
blob: 1bce87a786587b4691916b82225908c7992b9b18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build !noconntrack

package collector

import (
	"encoding/xml"
	"os/exec"
	"strconv"
	"time"

	"github.com/go-kit/kit/log"
	"github.com/prometheus/client_golang/prometheus"
)

type ConntrackStats struct {
	CollectTime int64
	Flows       []FlowRecord
}

type FlowRecord struct {
	L3Proto    string
	L4Proto    string
	SourceAddr string
	SourcePort int
	DestAddr   string
	DestPort   int
	PacketsIn  int64
	PacketsOut int64
	BytesIn    int64
	BytesOut   int64
}

func (m *ConntrackStats) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	m.CollectTime = time.Now().Unix()

	rd := struct {
		Flows []struct {
			Metas []struct {
				Direction  string `xml:"direction,attr"`
				Layer3Meta struct {
					ProtoName  string `xml:"protoname,attr"`
					SourceAddr string `xml:"src"`
					DestAddr   string `xml:"dst"`
				} `xml:"layer3"`
				Layer4Meta struct {
					ProtoName  string `xml:"protoname,attr"`
					SourcePort int    `xml:"sport"`
					DestPort   int    `xml:"dport"`
				} `xml:"layer4"`
				Packets int64 `xml:"counters>packets"`
				Bytes   int64 `xml:"counters>bytes"`
			} `xml:"meta"`
		} `xml:"flow"`
	}{}

	err := d.DecodeElement(&rd, &start)
	if err != nil {
		return err
	}

	for _, f := range rd.Flows {
		or := FlowRecord{}

		for _, m := range f.Metas {
			if m.Direction == "original" {
				or.L3Proto = m.Layer3Meta.ProtoName
				or.L4Proto = m.Layer4Meta.ProtoName
				or.SourceAddr = m.Layer3Meta.SourceAddr
				or.SourcePort = m.Layer4Meta.SourcePort
				or.DestAddr = m.Layer3Meta.DestAddr
				or.DestPort = m.Layer4Meta.DestPort
				or.PacketsIn = m.Packets
				or.BytesIn = m.Bytes
			} else if m.Direction == "reply" {
				or.PacketsOut = m.Packets
				or.BytesOut = m.Bytes
			}
		}

		m.Flows = append(m.Flows, or)
	}

	return nil
}

func loadStats(proto string, s *ConntrackStats) error {
	cmd := exec.Command("/usr/sbin/conntrack", "-L", "-f", proto, "-o", "xml")
	out, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}

	if err := cmd.Start(); err != nil {
		return err
	}

	dec := xml.NewDecoder(out)
	if err = dec.Decode(s); err != nil {
		return err
	}

	if err := cmd.Wait(); err != nil {
		return err
	}

	return nil
}

func init() {
	registerCollector("conntrack_exec", defaultDisabled, NewConntrackExecCollector)
}

func NewConntrackExecCollector(logger log.Logger) (Collector, error) {
	subsystem := "conntrack_exec"
	labels := []string{"l3", "l4", "saddr", "sport", "daddr", "dport"}

	return &conntrackExecCollector{
		bytesIn: prometheus.NewDesc(
			prometheus.BuildFQName(namespace, subsystem, "bytes_in"),
			"Conntrack bytes in for flow",
			labels, nil,
		),
		bytesOut: prometheus.NewDesc(
			prometheus.BuildFQName(namespace, subsystem, "bytes_out"),
			"Conntrack bytes out for flow",
			labels, nil,
		),
		packetsIn: prometheus.NewDesc(
			prometheus.BuildFQName(namespace, subsystem, "packets_in"),
			"Conntrack packets in for flow",
			labels, nil,
		),
		packetsOut: prometheus.NewDesc(
			prometheus.BuildFQName(namespace, subsystem, "packets_out"),
			"Conntrack packets out for flow",
			labels, nil,
		),
	}, nil
}

type conntrackExecCollector struct {
	bytesIn, bytesOut     *prometheus.Desc
	packetsIn, packetsOut *prometheus.Desc
	logger                log.Logger
}

func (c *conntrackExecCollector) Update(ch chan<- prometheus.Metric) error {
	stats := &ConntrackStats{}

	if err := loadStats("ipv4", stats); err != nil {
		return err
	}

	if err := loadStats("ipv6", stats); err != nil {
		return err
	}

	for _, f := range stats.Flows {
		ch <- prometheus.MustNewConstMetric(
			c.bytesIn, prometheus.CounterValue,
			float64(f.BytesIn),
			f.L3Proto, f.L4Proto, f.SourceAddr, strconv.Itoa(f.SourcePort), f.DestAddr, strconv.Itoa(f.DestPort),
		)
		ch <- prometheus.MustNewConstMetric(
			c.bytesOut, prometheus.CounterValue,
			float64(f.BytesOut),
			f.L3Proto, f.L4Proto, f.SourceAddr, strconv.Itoa(f.SourcePort), f.DestAddr, strconv.Itoa(f.DestPort),
		)
		ch <- prometheus.MustNewConstMetric(
			c.packetsIn, prometheus.CounterValue,
			float64(f.PacketsIn),
			f.L3Proto, f.L4Proto, f.SourceAddr, strconv.Itoa(f.SourcePort), f.DestAddr, strconv.Itoa(f.DestPort),
		)
		ch <- prometheus.MustNewConstMetric(
			c.packetsOut, prometheus.CounterValue,
			float64(f.PacketsOut),
			f.L3Proto, f.L4Proto, f.SourceAddr, strconv.Itoa(f.SourcePort), f.DestAddr, strconv.Itoa(f.DestPort),
		)
	}

	return nil
}