github.com/netdata/go.d.plugin@v0.58.1/modules/chrony/client.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package chrony
     4  
     5  import (
     6  	"fmt"
     7  	"net"
     8  
     9  	"github.com/facebook/time/ntp/chrony"
    10  )
    11  
    12  func newChronyClient(c Config) (chronyClient, error) {
    13  	conn, err := net.DialTimeout("udp", c.Address, c.Timeout.Duration)
    14  	if err != nil {
    15  		return nil, err
    16  	}
    17  
    18  	client := &simpleClient{
    19  		conn:   conn,
    20  		client: &chrony.Client{Connection: conn},
    21  	}
    22  	return client, nil
    23  }
    24  
    25  type simpleClient struct {
    26  	conn   net.Conn
    27  	client *chrony.Client
    28  }
    29  
    30  func (sc *simpleClient) Tracking() (*chrony.ReplyTracking, error) {
    31  	reply, err := sc.client.Communicate(chrony.NewTrackingPacket())
    32  	if err != nil {
    33  		return nil, err
    34  	}
    35  
    36  	tracking, ok := reply.(*chrony.ReplyTracking)
    37  	if !ok {
    38  		return nil, fmt.Errorf("unexpected reply type, want=%T, got=%T", &chrony.ReplyTracking{}, reply)
    39  	}
    40  	return tracking, nil
    41  }
    42  
    43  func (sc *simpleClient) Activity() (*chrony.ReplyActivity, error) {
    44  	reply, err := sc.client.Communicate(chrony.NewActivityPacket())
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  
    49  	activity, ok := reply.(*chrony.ReplyActivity)
    50  	if !ok {
    51  		return nil, fmt.Errorf("unexpected reply type, want=%T, got=%T", &chrony.ReplyActivity{}, reply)
    52  	}
    53  	return activity, nil
    54  }
    55  
    56  func (sc *simpleClient) Close() {
    57  	if sc.conn != nil {
    58  		_ = sc.conn.Close()
    59  		sc.conn = nil
    60  	}
    61  }