File: ifplugo.go

package info (click to toggle)
golang-github-satta-ifplugo 0.0~git20180801.8b80699-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 204 kB
  • sloc: ansic: 986; makefile: 5
file content (245 lines) | stat: -rw-r--r-- 7,106 bytes parent folder | download
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package ifplugo

// This file is part of ifplugo.
//
// ifplugo is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// ifplugo is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ifplugo; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.

/*
#cgo LDFLAGS: -ldaemon
#include <interface.h>
*/
import (
	"C"
)

import (
	"syscall"
	"time"

	"github.com/shirou/gopsutil/net"
	log "github.com/sirupsen/logrus"
)

// InterfaceStatus represents the link status of an interface.
type InterfaceStatus int

const (
	// InterfaceUnknown represents an interface with no assigned state.
	InterfaceUnknown InterfaceStatus = iota
	// InterfaceUp represents an interface with a cable connected.
	InterfaceUp
	// InterfaceDown represents an interface with no cable connected.
	InterfaceDown
	// InterfaceErr represents an interface with errors querying its status.
	InterfaceErr
)

var statusLookup = map[C.interface_status_t]InterfaceStatus{
	C.IFSTATUS_UP:   InterfaceUp,
	C.IFSTATUS_DOWN: InterfaceDown,
	C.IFSTATUS_ERR:  InterfaceErr,
}

func (s InterfaceStatus) String() string {
	switch s {
	case InterfaceUp:
		return "link"
	case InterfaceDown:
		return "no link"
	case InterfaceErr:
		return "error"
	default:
		return "unknown"
	}
}

// GetLinkStatus returns, for a given interface, the corresponding status code
// at the time of the call. If any error was encountered (e.g. invalid
// interface, etc.) we simply return ifplugo.InterfaceErr.
func GetLinkStatus(iface string) (InterfaceStatus, error) {
	fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM,
		syscall.IPPROTO_IP)
	if err != nil {
		return InterfaceErr, err
	}
	defer syscall.Close(fd)

	e := C.interface_detect_beat_ethtool(C.int(fd), C.CString(iface))
	if e == C.IFSTATUS_ERR {
		e = C.interface_detect_beat_mii(C.int(fd), C.CString(iface))
		if e == C.IFSTATUS_ERR {
			e = C.interface_detect_beat_wlan(C.int(fd), C.CString(iface))
			if e == C.IFSTATUS_ERR {
				e = C.interface_detect_beat_iff(C.int(fd), C.CString(iface))
			}
		}
	}

	return statusLookup[e], nil
}

// LinkStatusMonitor represents a concurrent software component that
// periodically checks a list of given interfaces and returns their link status
// via a specified channel.
type LinkStatusMonitor struct {
	PollPeriod             time.Duration
	LastStatus             map[string]InterfaceStatus
	LastStats              map[string]net.IOCountersStat
	checkIncomingDelta     bool
	checkIncomingThreshold uint64
	configuredByLink       map[string]bool
	OutChan                chan LinkStatusSample
	CloseChan              chan bool
	ClosedChan             chan bool
	Ifaces                 []string
}

// LinkStatusSample is a single description of the link status at a given time.
// Changed is set to true if the state is different than the previously emitted
// one.
type LinkStatusSample struct {
	Ifaces map[string]InterfaceStatus
}

// MakeLinkStatusMonitor creates a new LinkStatusMonitor, polling each interval
// given in pollPeriod for the status information of the interfaces given in
// ifaces and outputting results as a map of interface->status pairs in the
// channel outChan.
func MakeLinkStatusMonitor(pollPeriod time.Duration, ifaces []string,
	outChan chan LinkStatusSample) *LinkStatusMonitor {
	a := &LinkStatusMonitor{
		PollPeriod:       pollPeriod,
		OutChan:          outChan,
		CloseChan:        make(chan bool),
		ClosedChan:       make(chan bool),
		Ifaces:           ifaces,
		LastStatus:       make(map[string]InterfaceStatus),
		LastStats:        make(map[string]net.IOCountersStat),
		configuredByLink: make(map[string]bool),
	}
	return a
}

// CheckIncomingDelta allows to enable the optional behaviour to also consider
// an interface as 'up' if traffic is received on it. This is, for example,
// necessary in passive monitoring setups where there is no physical link
// detected (e.g. using taps that only provide RX lines).
func (a *LinkStatusMonitor) CheckIncomingDelta(val bool, threshold uint64) {
	a.checkIncomingDelta = val
	a.checkIncomingThreshold = threshold
}

func myDiffAbs(new, old uint64) uint64 {
	if new > old {
		return new - old
	}
	return 0
}

func (a *LinkStatusMonitor) flush() error {
	out := LinkStatusSample{
		Ifaces: make(map[string]InterfaceStatus),
	}

	// try to get status via link
	for _, iface := range a.Ifaces {
		v, err := GetLinkStatus(iface)
		if err != nil {
			out.Ifaces[iface] = InterfaceUnknown
		}
		out.Ifaces[iface] = v
		if v == InterfaceUp {
			// this interface has been seen up once via actual link status
			// let's record this fact so we won't override this from data
			// flow info
			if _, ok := a.configuredByLink[iface]; !ok {
				a.configuredByLink[iface] = true
			}
		}
		log.Debug("link status: ", iface, v)
	}

	// also try to determine status from data flow
	if a.checkIncomingDelta {
		ifstats, err := net.IOCounters(true)
		if err != nil {
			return err
		}
		for _, stat := range ifstats {
			for _, iface := range a.Ifaces {
				if stat.Name == iface {
					if _, ok := a.configuredByLink[iface]; ok {
						if a.configuredByLink[iface] {
							continue
						}
					}
					log.Debugf("%s, %s, %d/%d -> %d", iface, a.LastStatus[iface], stat.BytesRecv, a.LastStats[iface].BytesRecv, myDiffAbs(stat.BytesRecv, a.LastStats[iface].BytesRecv))
					if a.LastStatus[iface] != InterfaceUp {
						if myDiffAbs(stat.BytesRecv, a.LastStats[iface].BytesRecv) > a.checkIncomingThreshold {
							out.Ifaces[iface] = InterfaceUp
							log.Debugf("changed %s to up", iface)
						} else {
							out.Ifaces[iface] = a.LastStatus[iface]
						}
					} else {
						if myDiffAbs(stat.BytesRecv, a.LastStats[iface].BytesRecv) <= a.checkIncomingThreshold {
							out.Ifaces[iface] = InterfaceDown
							log.Debugf("changed %s to down", iface)
						} else {
							out.Ifaces[iface] = a.LastStatus[iface]
						}
					}
					a.LastStats[iface] = stat
				}
			}
		}
	}

	changed := false
	for iface := range out.Ifaces {
		if a.LastStatus[iface] != out.Ifaces[iface] {
			changed = true
			log.Debugf("status changed %s <-> %s", a.LastStatus[iface], out.Ifaces[iface])
			a.LastStatus[iface] = out.Ifaces[iface]
		}
	}

	if changed {
		a.OutChan <- out
	}
	return nil
}

// Run starts watching interfaces in the background.
func (a *LinkStatusMonitor) Run() {
	go func() {
		a.flush()
		for {
			select {
			case <-a.CloseChan:
				close(a.ClosedChan)
				return
			case <-time.After(a.PollPeriod):
				a.flush()
			}
		}
	}()
}

// Stop causes the monitor to cease monitoring interfaces.
func (a *LinkStatusMonitor) Stop() {
	close(a.CloseChan)
	<-a.ClosedChan
}