From 9d4946b4d3de7bef1c57a099b7129444f2cc0a19 Mon Sep 17 00:00:00 2001 From: Oleg Obleukhov Date: Mon, 23 Dec 2024 08:27:44 -0800 Subject: [PATCH] export uptime Summary: This will help us to estimate health of the device fleet Differential Revision: D67601592 --- calnex/api/api.go | 27 +++++++++++++++++++++++++++ calnex/api/api_test.go | 21 +++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/calnex/api/api.go b/calnex/api/api.go index cd438dc..556f229 100644 --- a/calnex/api/api.go +++ b/calnex/api/api.go @@ -82,6 +82,11 @@ type Version struct { Firmware string } +// Uptime is a struct representing Calnex uptime JSON response +type Uptime struct { + Uptime int64 +} + // GNSS is a struct representing Calnex GNSS JSON response type GNSS struct { AntennaStatus string @@ -461,6 +466,7 @@ const ( rebootURL = "https://%s/api/reboot?action=reboot" versionURL = "https://%s/api/version" + uptimeURL = "https://%s/api/uptime" firmwareURL = "https://%s/api/updatefirmware" certificateURL = "https://%s/api/installcertificate" licenseURL = "https://%s/api/option/load" @@ -908,3 +914,24 @@ func (a *API) PowerSupplyStatus() (*PowerSupplyStatus, error) { return p, nil } + +// FetchUptime returns uptime of the device +func (a *API) FetchUptime() (*Uptime, error) { + url := fmt.Sprintf(uptimeURL, a.source) + resp, err := a.Client.Get(url) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return nil, errors.New(http.StatusText(resp.StatusCode)) + } + + u := &Uptime{} + if err = json.NewDecoder(resp.Body).Decode(u); err != nil { + return nil, err + } + + return u, nil +} diff --git a/calnex/api/api_test.go b/calnex/api/api_test.go index 4acb202..c7d6120 100644 --- a/calnex/api/api_test.go +++ b/calnex/api/api_test.go @@ -835,3 +835,24 @@ func TestPowerSupplyStatusSentinel(t *testing.T) { require.NoError(t, err) require.Equal(t, expected, g) } + +func TestFetchUptime(t *testing.T) { + sampleResp := "{\"uptime\": 42}" + expected := &Uptime{ + Uptime: 42, + } + + ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, + r *http.Request) { + fmt.Fprintln(w, sampleResp) + })) + defer ts.Close() + + parsed, _ := url.Parse(ts.URL) + calnexAPI := NewAPI(parsed.Host, true, time.Second) + calnexAPI.Client = ts.Client() + + f, err := calnexAPI.FetchUptime() + require.NoError(t, err) + require.Equal(t, expected, f) +}