summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/chrony/client.go
blob: e850ff2394f84ee05434f2797459ed2b027fb516 (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
// SPDX-License-Identifier: GPL-3.0-or-later

package chrony

import (
	"fmt"
	"net"

	"github.com/facebook/time/ntp/chrony"
)

func newChronyClient(c Config) (chronyClient, error) {
	conn, err := net.DialTimeout("udp", c.Address, c.Timeout.Duration())
	if err != nil {
		return nil, err
	}

	client := &simpleClient{
		conn:   conn,
		client: &chrony.Client{Connection: conn},
	}
	return client, nil
}

type simpleClient struct {
	conn   net.Conn
	client *chrony.Client
}

func (sc *simpleClient) Tracking() (*chrony.ReplyTracking, error) {
	reply, err := sc.client.Communicate(chrony.NewTrackingPacket())
	if err != nil {
		return nil, err
	}

	tracking, ok := reply.(*chrony.ReplyTracking)
	if !ok {
		return nil, fmt.Errorf("unexpected reply type, want=%T, got=%T", &chrony.ReplyTracking{}, reply)
	}
	return tracking, nil
}

func (sc *simpleClient) Activity() (*chrony.ReplyActivity, error) {
	reply, err := sc.client.Communicate(chrony.NewActivityPacket())
	if err != nil {
		return nil, err
	}

	activity, ok := reply.(*chrony.ReplyActivity)
	if !ok {
		return nil, fmt.Errorf("unexpected reply type, want=%T, got=%T", &chrony.ReplyActivity{}, reply)
	}
	return activity, nil
}

func (sc *simpleClient) Close() {
	if sc.conn != nil {
		_ = sc.conn.Close()
		sc.conn = nil
	}
}