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

package ntpd

import (
	"net"
	"time"

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

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

	client := &ntpClient{
		conn:    conn,
		timeout: c.Timeout.Duration(),
		client:  &control.NTPClient{Connection: conn},
	}

	return client, nil
}

type ntpClient struct {
	conn    net.Conn
	timeout time.Duration
	client  *control.NTPClient
}

func (c *ntpClient) systemInfo() (map[string]string, error) {
	return c.peerInfo(0)
}

func (c *ntpClient) peerInfo(id uint16) (map[string]string, error) {
	msg := &control.NTPControlMsgHead{
		VnMode:        control.MakeVnMode(2, control.Mode),
		REMOp:         control.OpReadVariables,
		AssociationID: id,
	}

	if err := c.conn.SetDeadline(time.Now().Add(c.timeout)); err != nil {
		return nil, err
	}

	resp, err := c.client.Communicate(msg)
	if err != nil {
		return nil, err
	}

	return resp.GetAssociationInfo()
}

func (c *ntpClient) peerIDs() ([]uint16, error) {
	msg := &control.NTPControlMsgHead{
		VnMode: control.MakeVnMode(2, control.Mode),
		REMOp:  control.OpReadStatus,
	}

	if err := c.conn.SetDeadline(time.Now().Add(c.timeout)); err != nil {
		return nil, err
	}

	resp, err := c.client.Communicate(msg)
	if err != nil {
		return nil, err
	}

	peers, err := resp.GetAssociations()
	if err != nil {
		return nil, err
	}

	var ids []uint16
	for id := range peers {
		ids = append(ids, id)
	}

	return ids, nil
}

func (c *ntpClient) close() {
	if c.conn != nil {
		_ = c.conn.Close()
		c.conn = nil
	}
}