-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdhcp.go
More file actions
73 lines (64 loc) · 1.86 KB
/
dhcp.go
File metadata and controls
73 lines (64 loc) · 1.86 KB
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
package main
import (
"fmt"
"net"
"time"
"github.com/insomniacslk/dhcp/dhcpv4"
"github.com/insomniacslk/dhcp/dhcpv4/client4"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
var (
dhcpRequests = promauto.NewCounter(prometheus.CounterOpts{
Name: "observer_dhcp_requests",
Help: "Total number of sent DHCPv4 requests",
})
dhcpOffers = promauto.NewCounter(prometheus.CounterOpts{
Name: "observer_dhcp_offers",
Help: "Total number of received DHCPv4 offers",
})
dhcpFailures = promauto.NewCounter(prometheus.CounterOpts{
Name: "observer_dhcp_failures",
Help: "Total number of failed DHCPv4 handshakes",
})
dhcpHandshakeLatency = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "observer_dhcp_latency",
Help: "Time between DHCPv4 request and offer.",
})
dhcpLeaseTime = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "observer_dhcp_lease_time",
Help: "Time until DHCPv4 lease will be renewed.",
})
)
func init() {
prometheus.MustRegister(dhcpHandshakeLatency)
prometheus.MustRegister(dhcpLeaseTime)
}
func sampleDhcp(client client4.Client, verbose bool) (net.IP, int, error) {
dhcpRequests.Inc()
start := time.Now()
conversation, err := client.Exchange(iface)
if err != nil {
dhcpFailures.Inc()
return nil, 0, err
}
dhcpHandshakeLatency.Set(time.Since(start).Seconds())
var yourIPAddr net.IP
var prefixBits int
for _, packet := range conversation {
if verbose {
fmt.Println(packet.Summary())
}
if packet.MessageType() == dhcpv4.MessageTypeOffer {
dhcpOffers.Inc()
}
if packet.MessageType() == dhcpv4.MessageTypeAck {
if packet.Options.Has(dhcpv4.OptionIPAddressLeaseTime) {
dhcpLeaseTime.Set(packet.IPAddressLeaseTime(0).Seconds())
}
prefixBits, _ = packet.SubnetMask().Size()
yourIPAddr = packet.YourIPAddr
}
}
return yourIPAddr, prefixBits, err
}