Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add device last connected metrics #1515

Merged
merged 5 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions internal/application/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ func GetCommand(ctx context.Context, deviceName string, commandName string, quer

lc := bootstrapContainer.LoggingClientFrom(dic.Get)
lc.Debugf("GET Device Command successfully. Device: %s, Source: %s, %s: %s", deviceName, commandName, common.CorrelationHeader, utils.FromContext(ctx, common.CorrelationHeader))

cache.Devices().SetLastConnectedByName(deviceName)
return res, nil
}

Expand Down Expand Up @@ -93,6 +95,8 @@ func SetCommand(ctx context.Context, deviceName string, commandName string, quer

lc := bootstrapContainer.LoggingClientFrom(dic.Get)
lc.Debugf("SET Device Command successfully. Device: %s, Source: %s, %s: %s", deviceName, commandName, common.CorrelationHeader, utils.FromContext(ctx, common.CorrelationHeader))

cache.Devices().SetLastConnectedByName(deviceName)
return event, nil
}

Expand Down
81 changes: 76 additions & 5 deletions internal/cache/devices.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2020-2021 IOTech Ltd
// Copyright (C) 2020-2023 IOTech Ltd
//
// SPDX-License-Identifier: Apache-2.0

package cache

import (
"fmt"
"strings"
"sync"
"time"

bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/container"
"github.com/edgexfoundry/go-mod-bootstrap/v3/di"
"github.com/edgexfoundry/go-mod-core-contracts/v3/errors"
"github.com/edgexfoundry/go-mod-core-contracts/v3/models"

gometrics "github.com/rcrowley/go-metrics"
)

const (
deviceNameText = "{DeviceName}"
lastConnectedPrefix = "LastConnected-" + deviceNameText
)

var (
Expand All @@ -25,24 +36,56 @@ type DeviceCache interface {
Update(device models.Device) errors.EdgeX
RemoveByName(name string) errors.EdgeX
UpdateAdminState(name string, state models.AdminState) errors.EdgeX
SetLastConnectedByName(name string)
GetLastConnectedByName(name string) int64
}

type deviceCache struct {
deviceMap map[string]*models.Device // key is Device name
mutex sync.RWMutex
deviceMap map[string]*models.Device // key is Device name
mutex sync.RWMutex
dic *di.Container
lastConnected map[string]gometrics.Gauge
}

func newDeviceCache(devices []models.Device) DeviceCache {
func newDeviceCache(devices []models.Device, dic *di.Container) DeviceCache {
defaultSize := len(devices)
dMap := make(map[string]*models.Device, defaultSize)
for i, d := range devices {
dMap[d.Name] = &devices[i]
}

dc = &deviceCache{deviceMap: dMap}
dc = &deviceCache{deviceMap: dMap, dic: dic}
lastConnectedMetrics := make(map[string]gometrics.Gauge)
for _, d := range devices {
deviceMetric := gometrics.NewGauge()
registerMetric(d.Name, deviceMetric, dic)
lastConnectedMetrics[d.Name] = deviceMetric
}
dc.lastConnected = lastConnectedMetrics

return dc
}

func registerMetric(deviceName string, metric interface{}, dic *di.Container) {
metricsManager := bootstrapContainer.MetricsManagerFrom(dic.Get)
lc := bootstrapContainer.LoggingClientFrom(dic.Get)
registeredName := strings.Replace(lastConnectedPrefix, deviceNameText, deviceName, 1)

err := metricsManager.Register(registeredName, metric, nil)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tag is still needed. This allows for filtering on a dashboard such as Grafana.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, tag added back. Thanks.

if err != nil {
lc.Warnf("Unable to register %s metric. Metric will not be reported : %s", registeredName, err.Error())
} else {
lc.Infof("%s metric has been registered and will be reported (if enabled)", registeredName)
}
}

func unregisterMetric(deviceName string, dic *di.Container) {
metricsManager := bootstrapContainer.MetricsManagerFrom(dic.Get)
registeredName := strings.Replace(lastConnectedPrefix, deviceNameText, deviceName, 1)

metricsManager.Unregister(registeredName)
}

// ForName returns a Device with the given device name.
func (d *deviceCache) ForName(name string) (models.Device, bool) {
d.mutex.RLock()
Expand Down Expand Up @@ -85,6 +128,11 @@ func (d *deviceCache) add(device models.Device) errors.EdgeX {
}

d.deviceMap[device.Name] = &device

// register the lastConnected metric for the new added device
deviceMetric := gometrics.NewGauge()
registerMetric(device.Name, deviceMetric, d.dic)
d.lastConnected[device.Name] = deviceMetric
return nil
}

Expand Down Expand Up @@ -115,6 +163,11 @@ func (d *deviceCache) removeByName(name string) errors.EdgeX {
}

delete(d.deviceMap, name)

// unregister the lastConnected metric for the removed device
unregisterMetric(name, d.dic)
delete(d.lastConnected, name)

return nil
}

Expand Down Expand Up @@ -152,3 +205,21 @@ func CheckProfileNotUsed(profileName string) bool {
func Devices() DeviceCache {
return dc
}

// currentTimestamp returns the current timestamp in nanoseconds
var currentTimestamp = func() int64 {
return time.Now().UnixNano()
}

func (d *deviceCache) SetLastConnectedByName(name string) {
d.mutex.RLock()
defer d.mutex.RUnlock()

g := d.lastConnected[name]
g.Update(currentTimestamp())
}

func (d *deviceCache) GetLastConnectedByName(name string) int64 {
g := d.lastConnected[name]
return g.Value()
}
75 changes: 69 additions & 6 deletions internal/cache/devices_test.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
//
// Copyright (C) 2021 IOTech Ltd
// Copyright (C) 2021-2023 IOTech Ltd
//
// SPDX-License-Identifier: Apache-2.0

package cache

import (
"testing"
"time"

"github.com/edgexfoundry/device-sdk-go/v3/internal/config"
"github.com/edgexfoundry/device-sdk-go/v3/internal/container"

bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/container"
"github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/interfaces/mocks"
bootstrapConfig "github.com/edgexfoundry/go-mod-bootstrap/v3/config"
"github.com/edgexfoundry/go-mod-bootstrap/v3/di"
"github.com/edgexfoundry/go-mod-core-contracts/v3/clients/logger"
"github.com/edgexfoundry/go-mod-core-contracts/v3/models"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)

Expand All @@ -25,8 +36,33 @@ var newDevice = models.Device{
OperatingState: models.Unlocked,
}

func mockDic() *di.Container {
mockMetricsManager := &mocks.MetricsManager{}
mockMetricsManager.On("Register", mock.Anything, mock.Anything, mock.Anything).Return(nil)
mockMetricsManager.On("Unregister", mock.Anything)
return di.NewContainer(di.ServiceConstructorMap{
bootstrapContainer.MetricsManagerInterfaceName: func(get di.Get) interface{} {
return mockMetricsManager
},
bootstrapContainer.LoggingClientInterfaceName: func(get di.Get) interface{} {
return logger.NewMockClient()
},
container.ConfigurationName: func(get di.Get) interface{} {
return &config.ConfigurationStruct{
Writable: config.WritableInfo{
LogLevel: "INFO",
},
Service: bootstrapConfig.ServiceInfo{
EnableNameFieldEscape: true,
},
}
},
})
}

func Test_deviceCache_ForName(t *testing.T) {
newDeviceCache([]models.Device{testDevice})
dic := mockDic()
newDeviceCache([]models.Device{testDevice}, dic)

tests := []struct {
name string
Expand All @@ -48,14 +84,16 @@ func Test_deviceCache_ForName(t *testing.T) {
}

func Test_deviceCache_All(t *testing.T) {
newDeviceCache([]models.Device{testDevice})
dic := mockDic()
newDeviceCache([]models.Device{testDevice}, dic)

res := dc.All()
require.Equal(t, len(res), len(dc.deviceMap))
}

func Test_deviceCache_Add(t *testing.T) {
newDeviceCache([]models.Device{testDevice})
dic := mockDic()
newDeviceCache([]models.Device{testDevice}, dic)

tests := []struct {
name string
Expand All @@ -77,7 +115,8 @@ func Test_deviceCache_Add(t *testing.T) {
}

func Test_deviceCache_RemoveByName(t *testing.T) {
newDeviceCache([]models.Device{testDevice})
dic := mockDic()
newDeviceCache([]models.Device{testDevice}, dic)

tests := []struct {
name string
Expand All @@ -99,7 +138,8 @@ func Test_deviceCache_RemoveByName(t *testing.T) {
}

func Test_deviceCache_UpdateAdminState(t *testing.T) {
newDeviceCache([]models.Device{testDevice})
dic := mockDic()
newDeviceCache([]models.Device{testDevice}, dic)

tests := []struct {
name string
Expand All @@ -122,3 +162,26 @@ func Test_deviceCache_UpdateAdminState(t *testing.T) {
})
}
}

func Test_deviceCache_SetLastConnectedByName(t *testing.T) {
dic := mockDic()
newDeviceCache([]models.Device{testDevice}, dic)

// Make currentTimestamp return currentTimeInstant constant in unit test
currentTimeInstant := time.Now().UnixNano()
currentTimestamp = func() int64 {
return currentTimeInstant
}

dc.SetLastConnectedByName(TestDevice)
lastConnectedTime := dc.GetLastConnectedByName(TestDevice)
require.Equal(t, currentTimeInstant, lastConnectedTime)
}

func Test_deviceCache_GetLastConnectedByName(t *testing.T) {
dic := mockDic()
newDeviceCache([]models.Device{testDevice}, dic)

lastConnectedTime := dc.GetLastConnectedByName(TestDevice)
require.Equal(t, int64(0), lastConnectedTime)
}
4 changes: 2 additions & 2 deletions internal/cache/init.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// Copyright (C) 2020-2021 IOTech Ltd
// Copyright (C) 2020-2023 IOTech Ltd
//
// SPDX-License-Identifier: Apache-2.0

Expand Down Expand Up @@ -32,7 +32,7 @@ func InitCache(instanceName string, baseServiceName string, dic *di.Container) e
for i := range deviceRes.Devices {
devices[i] = dtos.ToDeviceModel(deviceRes.Devices[i])
}
newDeviceCache(devices)
newDeviceCache(devices, dic)

// init profile cache
profiles := make([]models.DeviceProfile, len(devices))
Expand Down
7 changes: 7 additions & 0 deletions internal/common/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,10 @@ func NewMockDIC() *di.Container {
pwcMock := &clientMocks.ProvisionWatcherClient{}
pwcMock.On("ProvisionWatchersByServiceName", context.Background(), TestDeviceService, 0, -1).Return(responses.MultiProvisionWatchersResponse{}, nil)

mockMetricsManager := &mocks.MetricsManager{}
mockMetricsManager.On("Register", mock.Anything, mock.Anything, mock.Anything).Return(nil)
mockMetricsManager.On("Unregister", mock.Anything)

return di.NewContainer(di.ServiceConstructorMap{
container.ConfigurationName: func(get di.Get) interface{} {
return configuration
Expand All @@ -141,6 +145,9 @@ func NewMockDIC() *di.Container {
bootstrapContainer.ProvisionWatcherClientName: func(get di.Get) interface{} {
return pwcMock
},
bootstrapContainer.MetricsManagerInterfaceName: func(get di.Get) interface{} {
return mockMetricsManager
},
})
}

Expand Down
9 changes: 9 additions & 0 deletions internal/controller/http/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"testing"

bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/container"
bootstrapMocks "github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/interfaces/mocks"
"github.com/edgexfoundry/go-mod-bootstrap/v3/di"
clientMocks "github.com/edgexfoundry/go-mod-core-contracts/v3/clients/interfaces/mocks"
"github.com/edgexfoundry/go-mod-core-contracts/v3/clients/logger"
Expand Down Expand Up @@ -170,6 +171,11 @@ func mockDic() *di.Container {
mockDriver.On("HandleReadCommands", driverErrorDevice, mock.Anything, mock.Anything).Return(nil, errors.New("ProtocolDriver returned error"))
mockDriver.On("HandleWriteCommands", testDevice, mock.Anything, mock.Anything, mock.Anything).Return(nil)
mockDriver.On("HandleWriteCommands", driverErrorDevice, mock.Anything, mock.Anything, mock.Anything).Return(errors.New("ProtocolDriver returned error"))

mockMetricsManager := &bootstrapMocks.MetricsManager{}
mockMetricsManager.On("Register", mock.Anything, mock.Anything, mock.Anything).Return(nil)
mockMetricsManager.On("Unregister", mock.Anything)

dic := di.NewContainer(di.ServiceConstructorMap{
container.ConfigurationName: func(get di.Get) any {
return &config.ConfigurationStruct{
Expand Down Expand Up @@ -199,6 +205,9 @@ func mockDic() *di.Container {
AdminState: models.Unlocked,
}
},
bootstrapContainer.MetricsManagerInterfaceName: func(get di.Get) interface{} {
return mockMetricsManager
},
})

return dic
Expand Down
10 changes: 10 additions & 0 deletions internal/provision/mockdic_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// -*- Mode: Go; indent-tabs-mode: t -*-
//
// # Copyright (C) 2023 Intel Corporation
// # Copyright (C) 2023 IOTech Ltd
//
// SPDX-License-Identifier: Apache-2.0
package provision
Expand All @@ -10,12 +11,14 @@ import (
"github.com/edgexfoundry/device-sdk-go/v3/internal/config"
"github.com/edgexfoundry/device-sdk-go/v3/internal/container"
bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/container"
bootstrapMocks "github.com/edgexfoundry/go-mod-bootstrap/v3/bootstrap/interfaces/mocks"
"github.com/edgexfoundry/go-mod-bootstrap/v3/di"
clientMocks "github.com/edgexfoundry/go-mod-core-contracts/v3/clients/interfaces/mocks"
"github.com/edgexfoundry/go-mod-core-contracts/v3/clients/logger"
"github.com/edgexfoundry/go-mod-core-contracts/v3/dtos"
"github.com/edgexfoundry/go-mod-core-contracts/v3/dtos/responses"
"github.com/edgexfoundry/go-mod-core-contracts/v3/models"
"github.com/stretchr/testify/mock"
)

const (
Expand Down Expand Up @@ -96,6 +99,10 @@ func NewMockDIC() (*di.Container, *clientMocks.DeviceProfileClient) {
pwcMock := &clientMocks.ProvisionWatcherClient{}
pwcMock.On("ProvisionWatchersByServiceName", context.Background(), TestDeviceService, 0, -1).Return(responses.MultiProvisionWatchersResponse{}, nil)

mockMetricsManager := &bootstrapMocks.MetricsManager{}
mockMetricsManager.On("Register", mock.Anything, mock.Anything, mock.Anything).Return(nil)
mockMetricsManager.On("Unregister", mock.Anything)

return di.NewContainer(di.ServiceConstructorMap{
container.ConfigurationName: func(get di.Get) interface{} {
return configuration
Expand All @@ -115,5 +122,8 @@ func NewMockDIC() (*di.Container, *clientMocks.DeviceProfileClient) {
bootstrapContainer.ProvisionWatcherClientName: func(get di.Get) interface{} {
return pwcMock
},
bootstrapContainer.MetricsManagerInterfaceName: func(get di.Get) interface{} {
return mockMetricsManager
},
}), dpcMock
}
Loading