github.com/netdata/go.d.plugin@v0.58.1/modules/ntpd/client.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package ntpd 4 5 import ( 6 "net" 7 "time" 8 9 "github.com/facebook/time/ntp/control" 10 ) 11 12 func newNTPClient(c Config) (ntpConn, error) { 13 conn, err := net.DialTimeout("udp", c.Address, c.Timeout.Duration) 14 if err != nil { 15 return nil, err 16 } 17 18 client := &ntpClient{ 19 conn: conn, 20 timeout: c.Timeout.Duration, 21 client: &control.NTPClient{Connection: conn}, 22 } 23 24 return client, nil 25 } 26 27 type ntpClient struct { 28 conn net.Conn 29 timeout time.Duration 30 client *control.NTPClient 31 } 32 33 func (c *ntpClient) systemInfo() (map[string]string, error) { 34 return c.peerInfo(0) 35 } 36 37 func (c *ntpClient) peerInfo(id uint16) (map[string]string, error) { 38 msg := &control.NTPControlMsgHead{ 39 VnMode: control.MakeVnMode(2, control.Mode), 40 REMOp: control.OpReadVariables, 41 AssociationID: id, 42 } 43 44 if err := c.conn.SetDeadline(time.Now().Add(c.timeout)); err != nil { 45 return nil, err 46 } 47 48 resp, err := c.client.Communicate(msg) 49 if err != nil { 50 return nil, err 51 } 52 53 return resp.GetAssociationInfo() 54 } 55 56 func (c *ntpClient) peerIDs() ([]uint16, error) { 57 msg := &control.NTPControlMsgHead{ 58 VnMode: control.MakeVnMode(2, control.Mode), 59 REMOp: control.OpReadStatus, 60 } 61 62 if err := c.conn.SetDeadline(time.Now().Add(c.timeout)); err != nil { 63 return nil, err 64 } 65 66 resp, err := c.client.Communicate(msg) 67 if err != nil { 68 return nil, err 69 } 70 71 peers, err := resp.GetAssociations() 72 if err != nil { 73 return nil, err 74 } 75 76 var ids []uint16 77 for id := range peers { 78 ids = append(ids, id) 79 } 80 81 return ids, nil 82 } 83 84 func (c *ntpClient) close() { 85 if c.conn != nil { 86 _ = c.conn.Close() 87 c.conn = nil 88 } 89 }