diff --git a/go.mod b/go.mod index ac99175ff..a37a21264 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/edgexfoundry/device-sdk-go require ( github.com/OneOfOne/xxhash v1.2.6 github.com/edgexfoundry/go-mod-bootstrap v0.0.26 - github.com/edgexfoundry/go-mod-core-contracts v0.1.36 + github.com/edgexfoundry/go-mod-core-contracts v0.1.52 github.com/edgexfoundry/go-mod-registry v0.1.17 github.com/google/uuid v1.1.0 github.com/gorilla/mux v1.7.1 diff --git a/internal/cache/devices_test.go b/internal/cache/devices_test.go index bad9c5ad5..9f9db40b8 100644 --- a/internal/cache/devices_test.go +++ b/internal/cache/devices_test.go @@ -10,11 +10,12 @@ import ( "context" "testing" - "github.com/edgexfoundry/device-sdk-go/internal/common" - "github.com/edgexfoundry/device-sdk-go/internal/mock" contract "github.com/edgexfoundry/go-mod-core-contracts/models" "github.com/google/uuid" "github.com/stretchr/testify/assert" + + "github.com/edgexfoundry/device-sdk-go/internal/common" + "github.com/edgexfoundry/device-sdk-go/internal/mock" ) var ds []contract.Device @@ -23,7 +24,7 @@ func init() { common.ServiceName = "device-cache-test" common.DeviceClient = &mock.DeviceClientMock{} ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - ds, _ = common.DeviceClient.DevicesForServiceByName(common.ServiceName, ctx) + ds, _ = common.DeviceClient.DevicesForServiceByName(ctx, common.ServiceName) } func TestNewDeviceCache(t *testing.T) { diff --git a/internal/cache/init.go b/internal/cache/init.go index d76ac0c67..bebbc89f4 100644 --- a/internal/cache/init.go +++ b/internal/cache/init.go @@ -32,14 +32,14 @@ func InitCache() { } newValueDescriptorCache(vds) - ds, err := common.DeviceClient.DevicesForServiceByName(common.ServiceName, ctx) + ds, err := common.DeviceClient.DevicesForServiceByName(ctx, common.ServiceName) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Device cache initialization failed: %v", err)) ds = make([]contract.Device, 0) } newDeviceCache(ds) - pws, err := common.ProvisionWatcherClient.ProvisionWatchersForServiceByName(common.ServiceName, ctx) + pws, err := common.ProvisionWatcherClient.ProvisionWatchersForServiceByName(ctx, common.ServiceName) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Provision Watcher cache initialization failed %v", err)) pws = make([]contract.ProvisionWatcher, 0) diff --git a/internal/cache/init_test.go b/internal/cache/init_test.go index 6da74b030..5da0f15e0 100644 --- a/internal/cache/init_test.go +++ b/internal/cache/init_test.go @@ -10,11 +10,12 @@ import ( "context" "testing" - "github.com/edgexfoundry/device-sdk-go/internal/common" - "github.com/edgexfoundry/device-sdk-go/internal/mock" contract "github.com/edgexfoundry/go-mod-core-contracts/models" "github.com/google/uuid" "github.com/stretchr/testify/assert" + + "github.com/edgexfoundry/device-sdk-go/internal/common" + "github.com/edgexfoundry/device-sdk-go/internal/mock" ) func TestInitCache(t *testing.T) { @@ -29,7 +30,7 @@ func TestInitCache(t *testing.T) { t.Errorf("the expected number of valuedescriptors in cache is %d but got: %d:", len(vdsBeforeAddingToCache), vl) } - dsBeforeAddingToCache, _ := common.DeviceClient.DevicesForServiceByName(common.ServiceName, ctx) + dsBeforeAddingToCache, _ := common.DeviceClient.DevicesForServiceByName(ctx, common.ServiceName) if dl := len(Devices().All()); dl != len(dsBeforeAddingToCache) { t.Errorf("the expected number of devices in cache is %d but got: %d:", len(dsBeforeAddingToCache), dl) } diff --git a/internal/cache/provisionwatchers_test.go b/internal/cache/provisionwatchers_test.go index 4e6d6c88d..66e14b0e8 100644 --- a/internal/cache/provisionwatchers_test.go +++ b/internal/cache/provisionwatchers_test.go @@ -10,11 +10,12 @@ import ( "context" "testing" - "github.com/edgexfoundry/device-sdk-go/internal/common" - "github.com/edgexfoundry/device-sdk-go/internal/mock" contract "github.com/edgexfoundry/go-mod-core-contracts/models" "github.com/google/uuid" "github.com/stretchr/testify/assert" + + "github.com/edgexfoundry/device-sdk-go/internal/common" + "github.com/edgexfoundry/device-sdk-go/internal/mock" ) var pws []contract.ProvisionWatcher @@ -23,7 +24,7 @@ func init() { common.ServiceName = "watcher-cache-test" common.ProvisionWatcherClient = &mock.ProvisionWatcherClientMock{} ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - pws, _ = common.ProvisionWatcherClient.ProvisionWatchersForServiceByName(common.ServiceName, ctx) + pws, _ = common.ProvisionWatcherClient.ProvisionWatchersForServiceByName(ctx, common.ServiceName) } func TestNewProvisionWatcherCache(t *testing.T) { diff --git a/internal/clients/init.go b/internal/clients/init.go index 5b29331da..d2c0be53c 100644 --- a/internal/clients/init.go +++ b/internal/clients/init.go @@ -8,29 +8,27 @@ package clients import ( + "context" "fmt" - "net" "net/http" "sync" "time" - "github.com/edgexfoundry/device-sdk-go/internal/common" - "github.com/edgexfoundry/device-sdk-go/internal/endpoint" "github.com/edgexfoundry/go-mod-core-contracts/clients" "github.com/edgexfoundry/go-mod-core-contracts/clients/coredata" "github.com/edgexfoundry/go-mod-core-contracts/clients/general" "github.com/edgexfoundry/go-mod-core-contracts/clients/metadata" - "github.com/edgexfoundry/go-mod-core-contracts/clients/types" -) -const clientCount int = 8 + "github.com/edgexfoundry/device-sdk-go/internal/common" + "github.com/edgexfoundry/device-sdk-go/internal/urlclient" +) // InitDependencyClients triggers Service Client Initializer to establish connection to Metadata and Core Data Services // through Metadata Client and Core Data Client. // Service Client Initializer also needs to check the service status of Metadata and Core Data Services, // because they are important dependencies of Device Service. // The initialization process should be pending until Metadata Service and Core Data Service are both available. -func InitDependencyClients() error { +func InitDependencyClients(ctx context.Context, waitGroup *sync.WaitGroup) error { if err := validateClientConfig(); err != nil { return err } @@ -39,7 +37,7 @@ func InitDependencyClients() error { return err } - initializeClients() + initializeClients(ctx, waitGroup) common.LoggingClient.Info("Service clients initialize successful.") return nil @@ -155,71 +153,78 @@ func checkServiceAvailableViaRegistry(serviceId string) bool { return true } -func checkConsulAvailable() bool { - addr := fmt.Sprintf("%v:%v", common.CurrentConfig.Registry.Host, common.CurrentConfig.Registry.Port) - conn, err := net.Dial("tcp", addr) - if err != nil { - common.LoggingClient.Error(fmt.Sprintf("Consul cannot be reached, address: %v and error is \"%v\" ", addr, err.Error())) - return false - } - conn.Close() - return true -} - -func initializeClients() { - var waitGroup sync.WaitGroup - waitGroup.Add(clientCount) - - endpoint := &endpoint.Endpoint{RegistryClient: common.RegistryClient, WG: &waitGroup} - metaAddr := common.CurrentConfig.Clients[common.ClientMetadata].Url() - dataAddr := common.CurrentConfig.Clients[common.ClientData].Url() - isRegistry := common.RegistryClient != nil - - params := types.EndpointParams{ - UseRegistry: isRegistry, - Interval: 15, - } - +func initializeClients(ctx context.Context, waitGroup *sync.WaitGroup) { // initialize Core Metadata clients - params.ServiceKey = clients.CoreMetaDataServiceKey - - params.Path = clients.ApiAddressableRoute - params.Url = metaAddr + params.Path - common.AddressableClient = metadata.NewAddressableClient(params, endpoint) - - params.Path = clients.ApiDeviceRoute - params.Url = metaAddr + params.Path - common.DeviceClient = metadata.NewDeviceClient(params, endpoint) - - params.Path = clients.ApiDeviceServiceRoute - params.Url = metaAddr + params.Path - common.DeviceServiceClient = metadata.NewDeviceServiceClient(params, endpoint) - - params.Path = clients.ApiDeviceProfileRoute - params.Url = metaAddr + params.Path - common.DeviceProfileClient = metadata.NewDeviceProfileClient(params, endpoint) - - params.Path = clients.ApiConfigRoute - params.Url = metaAddr - common.MetadataGeneralClient = general.NewGeneralClient(params, endpoint) - - params.Path = clients.ApiProvisionWatcherRoute - params.Url = metaAddr + params.Path - common.ProvisionWatcherClient = metadata.NewProvisionWatcherClient(params, endpoint) + common.AddressableClient = metadata.NewAddressableClient( + urlclient.NewMetadata( + ctx, + common.RegistryClient, + waitGroup, + clients.ApiAddressableRoute, + ), + ) + + common.DeviceClient = metadata.NewDeviceClient( + urlclient.NewMetadata( + ctx, + common.RegistryClient, + waitGroup, + clients.ApiDeviceRoute, + ), + ) + + common.DeviceServiceClient = metadata.NewDeviceServiceClient( + urlclient.NewMetadata( + ctx, + common.RegistryClient, + waitGroup, + clients.ApiDeviceServiceRoute, + ), + ) + + common.DeviceProfileClient = metadata.NewDeviceProfileClient( + urlclient.NewMetadata( + ctx, + common.RegistryClient, + waitGroup, + clients.ApiDeviceProfileRoute, + ), + ) + + common.MetadataGeneralClient = general.NewGeneralClient( + urlclient.NewMetadata( + ctx, + common.RegistryClient, + waitGroup, + clients.ApiConfigRoute, + ), + ) + + common.ProvisionWatcherClient = metadata.NewProvisionWatcherClient( + urlclient.NewMetadata( + ctx, + common.RegistryClient, + waitGroup, + clients.ApiProvisionWatcherRoute, + ), + ) // initialize Core Data clients - params.ServiceKey = clients.CoreDataServiceKey - - params.Path = clients.ApiEventRoute - params.Url = dataAddr + params.Path - common.EventClient = coredata.NewEventClient(params, endpoint) - - params.Path = common.APIValueDescriptorRoute - params.Url = dataAddr + params.Path - common.ValueDescriptorClient = coredata.NewValueDescriptorClient(params, endpoint) - - if isRegistry { - // wait for the first endpoint discovery to make sure all clients work - waitGroup.Wait() - } + common.EventClient = coredata.NewEventClient( + urlclient.NewData( + ctx, + common.RegistryClient, + waitGroup, + clients.ApiEventRoute, + ), + ) + + common.ValueDescriptorClient = coredata.NewValueDescriptorClient( + urlclient.NewData( + ctx, + common.RegistryClient, + waitGroup, + common.APIValueDescriptorRoute, + ), + ) } diff --git a/internal/common/utils.go b/internal/common/utils.go index c0e0ba88f..46a974158 100644 --- a/internal/common/utils.go +++ b/internal/common/utils.go @@ -17,10 +17,11 @@ import ( "sync" "time" - dsModels "github.com/edgexfoundry/device-sdk-go/pkg/models" "github.com/edgexfoundry/go-mod-core-contracts/clients" contract "github.com/edgexfoundry/go-mod-core-contracts/models" "github.com/google/uuid" + + dsModels "github.com/edgexfoundry/device-sdk-go/pkg/models" ) var ( @@ -78,12 +79,12 @@ func SendEvent(event *dsModels.Event) { LoggingClient.Debug("SendEvent: EventClient.MarshalEvent passed through encoded event", clients.CorrelationHeader, correlation) } // Call AddBytes to post event to core data - responseBody, errPost := EventClient.AddBytes(event.EncodedEvent, ctx) + responseBody, errPost := EventClient.AddBytes(ctx, event.EncodedEvent) if errPost != nil { LoggingClient.Error("SendEvent Failed to push event", "device", event.Device, "response", responseBody, "error", errPost) } else { - LoggingClient.Info("SendEvent: Pushed event to core data", clients.ContentType, clients.FromContext(clients.ContentType, ctx), clients.CorrelationHeader, correlation) - LoggingClient.Trace("SendEvent: Pushed this event to core data", clients.ContentType, clients.FromContext(clients.ContentType, ctx), clients.CorrelationHeader, correlation, "event", event) + LoggingClient.Info("SendEvent: Pushed event to core data", clients.ContentType, clients.FromContext(ctx, clients.ContentType), clients.CorrelationHeader, correlation) + LoggingClient.Trace("SendEvent: Pushed this event to core data", clients.ContentType, clients.FromContext(ctx, clients.ContentType), clients.CorrelationHeader, correlation, "event", event) } } @@ -270,7 +271,7 @@ func FilterQueryParams(queryParams string) url.Values { LoggingClient.Error("Error parsing query parameters: %s\n", err) } // Filter out parameters with predefined prefix - for k, _ := range m { + for k := range m { if strings.HasPrefix(k, SDKReservedPrefix) { delete(m, k) } @@ -286,7 +287,7 @@ func UpdateLastConnected(name string) { } t := time.Now().UnixNano() / int64(time.Millisecond) - err := DeviceClient.UpdateLastConnectedByName(name, t, context.Background()) + err := DeviceClient.UpdateLastConnectedByName(context.Background(), name, t) if err != nil { LoggingClient.Error("Failed to update last connected value for device: " + name) } diff --git a/internal/endpoint/endpoint.go b/internal/endpoint/endpoint.go index b6a83c84b..4dc2f842a 100644 --- a/internal/endpoint/endpoint.go +++ b/internal/endpoint/endpoint.go @@ -2,59 +2,80 @@ // // Copyright (C) 2018 IOTech Ltd // Copyright (c) 2019 Intel Corporation +// Copyright (c) 2020 Dell Inc. // // SPDX-License-Identifier: Apache-2.0 package endpoint import ( + "context" "fmt" - "os" "sync" "time" - "github.com/edgexfoundry/go-mod-core-contracts/clients/types" + "github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces" "github.com/edgexfoundry/go-mod-registry/registry" ) type Endpoint struct { - RegistryClient registry.Client - passFirstRun bool - WG *sync.WaitGroup + ctx context.Context + wg *sync.WaitGroup + registryClient registry.Client + serviceKey string // The key of the service as found in the service registry (e.g. Consul) + path string // The path to the service's endpoint following port number in the URL + interval int // The interval in milliseconds governing how often the client polls to keep the endpoint current + +} + +func New( + ctx context.Context, + wg *sync.WaitGroup, + registryClient registry.Client, + serviceKey string, + path string, + interval int) *Endpoint { + + return &Endpoint{ + ctx: ctx, + wg: wg, + registryClient: registryClient, + serviceKey: serviceKey, + path: path, + interval: interval, + } } -func (e Endpoint) Monitor(params types.EndpointParams) chan string { - ch := make(chan string, 1) - ch <- e.fetch(params) +func (e Endpoint) Monitor() chan interfaces.URLStream { + ch := make(chan interfaces.URLStream) + ticker := time.NewTicker(time.Millisecond * time.Duration(e.interval)) + e.wg.Add(1) go func() { + defer e.wg.Done() + + // run fetchURL once before looping so we get the first check before the first timer interval + e.fetchURL(ch) for { - url, err := e.buildURL(params) - if err != nil { - fmt.Fprintln(os.Stdout, err.Error()) + select { + case <-e.ctx.Done(): + ticker.Stop() + return + + case <-ticker.C: + e.fetchURL(ch) } - ch <- url - time.Sleep(time.Second * time.Duration(params.Interval)) } }() + return ch } -func (e Endpoint) fetch(params types.EndpointParams) string { - url, err := e.buildURL(params) +func (e Endpoint) fetchURL(ch chan interfaces.URLStream) { + endpoint, err := (e.registryClient).GetServiceEndpoint(e.serviceKey) if err != nil { - fmt.Fprintln(os.Stdout, err.Error()) + _, _ = fmt.Println(fmt.Errorf("unable to get service endpoint for %s: %s", e.serviceKey, err.Error())) + return } - return url -} -func (e Endpoint) buildURL(params types.EndpointParams) (string, error) { - if e.RegistryClient != nil { - endpoint, err := (e.RegistryClient).GetServiceEndpoint(params.ServiceKey) - if err != nil { - return "", fmt.Errorf("unable to get Service endpoint for %s: %s", params.ServiceKey, err.Error()) - } - return fmt.Sprintf("http://%s:%v%s", endpoint.Host, endpoint.Port, params.Path), nil - } else { - return "", fmt.Errorf("unable to get Service endpoint for %s: Registry client is nil", params.ServiceKey) - } + ch <- interfaces.URLStream(fmt.Sprintf("http://%s:%v%s", endpoint.Host, endpoint.Port, e.path)) } diff --git a/internal/handler/callback/device.go b/internal/handler/callback/device.go index 313073d7e..38fc08954 100644 --- a/internal/handler/callback/device.go +++ b/internal/handler/callback/device.go @@ -22,7 +22,7 @@ import ( func handleDevice(method string, id string) common.AppError { ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) if method == http.MethodPost { - device, err := common.DeviceClient.Device(id, ctx) + device, err := common.DeviceClient.Device(ctx, id) if err != nil { appErr := common.NewBadRequestError(err.Error(), err) common.LoggingClient.Error(fmt.Sprintf("Cannot find the device %s from Core Metadata: %v", id, err)) @@ -63,7 +63,7 @@ func handleDevice(method string, id string) common.AppError { common.LoggingClient.Debug(fmt.Sprintf("Handler - starting AutoEvents for device %s", device.Name)) autoevent.GetManager().RestartForDevice(device.Name) } else if method == http.MethodPut { - device, err := common.DeviceClient.Device(id, ctx) + device, err := common.DeviceClient.Device(ctx, id) if err != nil { appErr := common.NewBadRequestError(err.Error(), err) common.LoggingClient.Error(fmt.Sprintf("Cannot find the device %s from Core Metadata: %v", id, err)) diff --git a/internal/handler/callback/profile.go b/internal/handler/callback/profile.go index 300c11636..b836efe6a 100644 --- a/internal/handler/callback/profile.go +++ b/internal/handler/callback/profile.go @@ -21,7 +21,7 @@ import ( func handleProfile(method string, id string) common.AppError { if method == http.MethodPut { ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - profile, err := common.DeviceProfileClient.DeviceProfile(id, ctx) + profile, err := common.DeviceProfileClient.DeviceProfile(ctx, id) if err != nil { appErr := common.NewBadRequestError(err.Error(), err) common.LoggingClient.Error(fmt.Sprintf("Cannot find the device profile %s from Core Metadata: %v", id, err)) diff --git a/internal/handler/callback/provisionwatcher.go b/internal/handler/callback/provisionwatcher.go index cb6f9c809..9ac720d8d 100644 --- a/internal/handler/callback/provisionwatcher.go +++ b/internal/handler/callback/provisionwatcher.go @@ -35,7 +35,7 @@ func handleProvisionWatcher(method string, id string) common.AppError { } func handlePostCallback(ctx context.Context, id string) common.AppError { - pw, err := common.ProvisionWatcherClient.ProvisionWatcher(id, ctx) + pw, err := common.ProvisionWatcherClient.ProvisionWatcher(ctx, id) if err != nil { appErr := common.NewBadRequestError(err.Error(), err) common.LoggingClient.Error(fmt.Sprintf("Cannot find provisionwatcher %s in Core Metadata: %v", id, err)) @@ -55,7 +55,7 @@ func handlePostCallback(ctx context.Context, id string) common.AppError { } func handlePutCallback(ctx context.Context, id string) common.AppError { - pw, err := common.ProvisionWatcherClient.ProvisionWatcher(id, ctx) + pw, err := common.ProvisionWatcherClient.ProvisionWatcher(ctx, id) if err != nil { appErr := common.NewBadRequestError(err.Error(), err) common.LoggingClient.Error(fmt.Sprintf("Cannot find provisionwatcher %s in Core Metadata: %v", id, err)) diff --git a/internal/handler/command_test.go b/internal/handler/command_test.go index 57ee2d1b8..9d1dce4d0 100644 --- a/internal/handler/command_test.go +++ b/internal/handler/command_test.go @@ -12,14 +12,15 @@ import ( "strings" "testing" - "github.com/edgexfoundry/device-sdk-go/internal/cache" - "github.com/edgexfoundry/device-sdk-go/internal/common" - "github.com/edgexfoundry/device-sdk-go/internal/mock" - dsModels "github.com/edgexfoundry/device-sdk-go/pkg/models" "github.com/edgexfoundry/go-mod-core-contracts/clients/logger" contract "github.com/edgexfoundry/go-mod-core-contracts/models" "github.com/google/uuid" "github.com/stretchr/testify/assert" + + "github.com/edgexfoundry/device-sdk-go/internal/cache" + "github.com/edgexfoundry/device-sdk-go/internal/common" + "github.com/edgexfoundry/device-sdk-go/internal/mock" + dsModels "github.com/edgexfoundry/device-sdk-go/pkg/models" ) const ( @@ -70,7 +71,7 @@ func init() { operationSetFloat64, _ = pc.ResourceOperation(mock.ProfileFloat, mock.ResourceObjectFloat64, methodSet) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - ds, _ = common.DeviceClient.DevicesForServiceByName(common.ServiceName, ctx) + ds, _ = common.DeviceClient.DevicesForServiceByName(ctx, common.ServiceName) deviceIntegerGenerator = ds[1] deviceInfo := common.DeviceInfo{DataTransform: true, MaxCmdOps: 128} @@ -248,7 +249,7 @@ func TestParseWriteParams(t *testing.T) { {"InvalidWriteParam", profileName, ros, `{"NotFound":"true"}`, true}, {"InvalidWriteParamType", profileName, ros, `{"RandomValue_Int8":"abc"}`, true}, {"ValueMappingPass", profileName, rosTestMappingPass, `{"ResourceTestMapping_Pass":"Pass"}`, false}, - //The expectErr on the test below is false because parseWriteParams does NOT throw an error when there is no mapping value matched + // The expectErr on the test below is false because parseWriteParams does NOT throw an error when there is no mapping value matched {"ValueMappingFail", profileName, rosTestMappingFail, `{"ResourceTestMapping_Fail":"123"}`, false}, {"ParseParamsFail", profileName, ros, ``, true}, {"NoRequestParameter", profileName, ros, `{}`, true}, @@ -282,10 +283,10 @@ func TestExecReadCmd(t *testing.T) { {"CmdNotFound", &deviceIntegerGenerator, "InexistentCmd", "", true}, {"ValueTransformFail", &deviceIntegerGenerator, "ResourceTestTransform_Fail", "", true}, {"ValueAssertionPass", &deviceIntegerGenerator, "ResourceTestAssertion_Pass", "", false}, - //The expectErr on the test below is false because execReadCmd does NOT throw an error when assertion failed + // The expectErr on the test below is false because execReadCmd does NOT throw an error when assertion failed {"ValueAssertionFail", &deviceIntegerGenerator, "ResourceTestAssertion_Fail", "", false}, {"ValueMappingPass", &deviceIntegerGenerator, "ResourceTestMapping_Pass", "", false}, - //The expectErr on the test below is false because execReadCmd does NOT throw an error when there is no mapping value matched + // The expectErr on the test below is false because execReadCmd does NOT throw an error when there is no mapping value matched {"ValueMappingFail", &deviceIntegerGenerator, "ResourceTestMapping_Fail", "", false}, {"NoDeviceResourceForOperation", &deviceIntegerGenerator, "NoDeviceResourceForOperation", "", true}, {"NoDeviceResourceForResult", &deviceIntegerGenerator, "NoDeviceResourceForResult", "", true}, @@ -309,7 +310,7 @@ func TestExecReadCmd(t *testing.T) { t.Errorf("%s expectErr:%v no error thrown", tt.testName, tt.expectErr) return } - //The way to determine whether the assertion passed or failed is to see the return value contains "Assertion failed" or not + // The way to determine whether the assertion passed or failed is to see the return value contains "Assertion failed" or not if tt.testName == "ValueAssertionPass" && strings.Contains(v.Readings[0].Value, "Assertion failed") { t.Errorf("%s expect data assertion pass", tt.testName) } diff --git a/internal/mock/mock_deviceclient.go b/internal/mock/mock_deviceclient.go index a4049d217..092198c98 100644 --- a/internal/mock/mock_deviceclient.go +++ b/internal/mock/mock_deviceclient.go @@ -33,60 +33,60 @@ var ( type DeviceClientMock struct{} -func (dc *DeviceClientMock) Add(dev *contract.Device, ctx context.Context) (string, error) { +func (dc *DeviceClientMock) Add(_ context.Context, _ *contract.Device) (string, error) { panic("implement me") } -func (dc *DeviceClientMock) Delete(id string, ctx context.Context) error { +func (dc *DeviceClientMock) Delete(_ context.Context, _ string) error { panic("implement me") } -func (dc *DeviceClientMock) DeleteByName(name string, ctx context.Context) error { +func (dc *DeviceClientMock) DeleteByName(_ context.Context, _ string) error { panic("implement me") } -func (dc *DeviceClientMock) CheckForDevice(token string, ctx context.Context) (contract.Device, error) { +func (dc *DeviceClientMock) CheckForDevice(_ context.Context, _ string) (contract.Device, error) { panic("implement me") } -func (dc *DeviceClientMock) Device(id string, ctx context.Context) (contract.Device, error) { +func (dc *DeviceClientMock) Device(_ context.Context, id string) (contract.Device, error) { if id == InvalidDeviceId { return contract.Device{}, fmt.Errorf("invalid id") } return contract.Device{}, nil } -func (dc *DeviceClientMock) DeviceForName(name string, ctx context.Context) (contract.Device, error) { +func (dc *DeviceClientMock) DeviceForName(_ context.Context, name string) (contract.Device, error) { var device = contract.Device{Id: "5b977c62f37ba10e36673802", Name: name} var err error = nil if name == "" { - err = errors.New("Item not found") + err = errors.New("item not found") } return device, err } -func (dc *DeviceClientMock) Devices(ctx context.Context) ([]contract.Device, error) { +func (dc *DeviceClientMock) Devices(_ context.Context) ([]contract.Device, error) { panic("implement me") } -func (dc *DeviceClientMock) DevicesByLabel(label string, ctx context.Context) ([]contract.Device, error) { +func (dc *DeviceClientMock) DevicesByLabel(_ context.Context, _ string) ([]contract.Device, error) { panic("implement me") } -func (dc *DeviceClientMock) DevicesForProfile(profileid string, ctx context.Context) ([]contract.Device, error) { +func (dc *DeviceClientMock) DevicesForProfile(_ context.Context, _ string) ([]contract.Device, error) { panic("implement me") } -func (dc *DeviceClientMock) DevicesForProfileByName(profileName string, ctx context.Context) ([]contract.Device, error) { +func (dc *DeviceClientMock) DevicesForProfileByName(_ context.Context, _ string) ([]contract.Device, error) { panic("implement me") } -func (dc *DeviceClientMock) DevicesForService(serviceid string, ctx context.Context) ([]contract.Device, error) { +func (dc *DeviceClientMock) DevicesForService(_ context.Context, _ string) ([]contract.Device, error) { panic("implement me") } -func (dc *DeviceClientMock) DevicesForServiceByName(serviceName string, ctx context.Context) ([]contract.Device, error) { +func (dc *DeviceClientMock) DevicesForServiceByName(_ context.Context, _ string) ([]contract.Device, error) { err := populateDeviceMock() if err != nil { return nil, err @@ -100,39 +100,39 @@ func (dc *DeviceClientMock) DevicesForServiceByName(serviceName string, ctx cont }, nil } -func (dc *DeviceClientMock) Update(dev contract.Device, ctx context.Context) error { +func (dc *DeviceClientMock) Update(_ context.Context, _ contract.Device) error { return nil } -func (dc *DeviceClientMock) UpdateAdminState(id string, adminState string, ctx context.Context) error { +func (dc *DeviceClientMock) UpdateAdminState(_ context.Context, _ string, _ string) error { return nil } -func (dc *DeviceClientMock) UpdateAdminStateByName(name string, adminState string, ctx context.Context) error { +func (dc *DeviceClientMock) UpdateAdminStateByName(_ context.Context, _ string, _ string) error { return nil } -func (dc *DeviceClientMock) UpdateLastConnected(id string, time int64, ctx context.Context) error { +func (dc *DeviceClientMock) UpdateLastConnected(_ context.Context, _ string, _ int64) error { return nil } -func (dc *DeviceClientMock) UpdateLastConnectedByName(name string, time int64, ctx context.Context) error { +func (dc *DeviceClientMock) UpdateLastConnectedByName(_ context.Context, _ string, _ int64) error { return nil } -func (dc *DeviceClientMock) UpdateLastReported(id string, time int64, ctx context.Context) error { +func (dc *DeviceClientMock) UpdateLastReported(_ context.Context, _ string, _ int64) error { return nil } -func (dc *DeviceClientMock) UpdateLastReportedByName(name string, time int64, ctx context.Context) error { +func (dc *DeviceClientMock) UpdateLastReportedByName(_ context.Context, _ string, _ int64) error { return nil } -func (dc *DeviceClientMock) UpdateOpState(id string, opState string, ctx context.Context) error { +func (dc *DeviceClientMock) UpdateOpState(_ context.Context, _ string, _ string) error { return nil } -func (dc *DeviceClientMock) UpdateOpStateByName(name string, opState string, ctx context.Context) error { +func (dc *DeviceClientMock) UpdateOpStateByName(_ context.Context, _ string, _ string) error { return nil } @@ -147,20 +147,20 @@ func populateDeviceMock() error { if err != nil { return err } - json.Unmarshal(devices[DeviceBool], &ValidDeviceRandomBoolGenerator) - json.Unmarshal(profiles[DeviceBool], &ValidDeviceRandomBoolGenerator.Profile) - json.Unmarshal(devices[DeviceInt], &ValidDeviceRandomIntegerGenerator) - json.Unmarshal(profiles[DeviceInt], &ValidDeviceRandomIntegerGenerator.Profile) - json.Unmarshal(devices[DeviceUint], &ValidDeviceRandomUnsignedIntegerGenerator) - json.Unmarshal(profiles[DeviceUint], &ValidDeviceRandomUnsignedIntegerGenerator.Profile) - json.Unmarshal(devices[DeviceFloat], &ValidDeviceRandomFloatGenerator) - json.Unmarshal(profiles[DeviceFloat], &ValidDeviceRandomFloatGenerator.Profile) - json.Unmarshal(devices[DeviceFloat], &DuplicateDeviceRandomFloatGenerator) - json.Unmarshal(profiles[DeviceFloat], &DuplicateDeviceRandomFloatGenerator.Profile) - json.Unmarshal(devices[DeviceNew], &NewValidDevice) - json.Unmarshal(profiles[DeviceNew], &NewValidDevice.Profile) - json.Unmarshal(devices[DeviceNew02], &OperatingStateDisabled) - json.Unmarshal(profiles[DeviceNew], &OperatingStateDisabled.Profile) + _ = json.Unmarshal(devices[DeviceBool], &ValidDeviceRandomBoolGenerator) + _ = json.Unmarshal(profiles[DeviceBool], &ValidDeviceRandomBoolGenerator.Profile) + _ = json.Unmarshal(devices[DeviceInt], &ValidDeviceRandomIntegerGenerator) + _ = json.Unmarshal(profiles[DeviceInt], &ValidDeviceRandomIntegerGenerator.Profile) + _ = json.Unmarshal(devices[DeviceUint], &ValidDeviceRandomUnsignedIntegerGenerator) + _ = json.Unmarshal(profiles[DeviceUint], &ValidDeviceRandomUnsignedIntegerGenerator.Profile) + _ = json.Unmarshal(devices[DeviceFloat], &ValidDeviceRandomFloatGenerator) + _ = json.Unmarshal(profiles[DeviceFloat], &ValidDeviceRandomFloatGenerator.Profile) + _ = json.Unmarshal(devices[DeviceFloat], &DuplicateDeviceRandomFloatGenerator) + _ = json.Unmarshal(profiles[DeviceFloat], &DuplicateDeviceRandomFloatGenerator.Profile) + _ = json.Unmarshal(devices[DeviceNew], &NewValidDevice) + _ = json.Unmarshal(profiles[DeviceNew], &NewValidDevice.Profile) + _ = json.Unmarshal(devices[DeviceNew02], &OperatingStateDisabled) + _ = json.Unmarshal(profiles[DeviceNew], &OperatingStateDisabled.Profile) return nil } diff --git a/internal/mock/mock_deviceprofileclient.go b/internal/mock/mock_deviceprofileclient.go index f3dc0ed9a..ba2e84d66 100644 --- a/internal/mock/mock_deviceprofileclient.go +++ b/internal/mock/mock_deviceprofileclient.go @@ -26,23 +26,23 @@ var ( type DeviceProfileClientMock struct{} -func (DeviceProfileClientMock) Add(dp *contract.DeviceProfile, ctx context.Context) (string, error) { +func (DeviceProfileClientMock) Add(_ context.Context, _ *contract.DeviceProfile) (string, error) { panic("implement me") } -func (DeviceProfileClientMock) Delete(id string, ctx context.Context) error { +func (DeviceProfileClientMock) Delete(_ context.Context, _ string) error { panic("implement me") } -func (DeviceProfileClientMock) DeleteByName(name string, ctx context.Context) error { +func (DeviceProfileClientMock) DeleteByName(_ context.Context, _ string) error { panic("implement me") } -func (DeviceProfileClientMock) DeviceProfile(id string, ctx context.Context) (contract.DeviceProfile, error) { +func (DeviceProfileClientMock) DeviceProfile(_ context.Context, _ string) (contract.DeviceProfile, error) { panic("implement me") } -func (DeviceProfileClientMock) DeviceProfiles(ctx context.Context) ([]contract.DeviceProfile, error) { +func (DeviceProfileClientMock) DeviceProfiles(_ context.Context) ([]contract.DeviceProfile, error) { err := populateDeviceProfileMock() if err != nil { return nil, err @@ -55,19 +55,19 @@ func (DeviceProfileClientMock) DeviceProfiles(ctx context.Context) ([]contract.D }, nil } -func (DeviceProfileClientMock) DeviceProfileForName(name string, ctx context.Context) (contract.DeviceProfile, error) { +func (DeviceProfileClientMock) DeviceProfileForName(_ context.Context, _ string) (contract.DeviceProfile, error) { panic("implement me") } -func (DeviceProfileClientMock) Update(dp contract.DeviceProfile, ctx context.Context) error { +func (DeviceProfileClientMock) Update(_ context.Context, _ contract.DeviceProfile) error { panic("implement me") } -func (DeviceProfileClientMock) Upload(yamlString string, ctx context.Context) (string, error) { +func (DeviceProfileClientMock) Upload(_ context.Context, _ string) (string, error) { panic("implement me") } -func (DeviceProfileClientMock) UploadFile(yamlFilePath string, ctx context.Context) (string, error) { +func (DeviceProfileClientMock) UploadFile(_ context.Context, _ string) (string, error) { panic("implement me") } @@ -78,12 +78,12 @@ func populateDeviceProfileMock() error { if err != nil { return err } - json.Unmarshal(profiles[ProfileBool], &DeviceProfileRandomBoolGenerator) - json.Unmarshal(profiles[ProfileInt], &DeviceProfileRandomIntegerGenerator) - json.Unmarshal(profiles[ProfileUint], &DeviceProfileRandomUnsignedGenerator) - json.Unmarshal(profiles[ProfileFloat], &DeviceProfileRandomFloatGenerator) - json.Unmarshal(profiles[ProfileFloat], &DuplicateDeviceProfileRandomFloatGenerator) - json.Unmarshal(profiles[ProfileNew], &NewDeviceProfile) + _ = json.Unmarshal(profiles[ProfileBool], &DeviceProfileRandomBoolGenerator) + _ = json.Unmarshal(profiles[ProfileInt], &DeviceProfileRandomIntegerGenerator) + _ = json.Unmarshal(profiles[ProfileUint], &DeviceProfileRandomUnsignedGenerator) + _ = json.Unmarshal(profiles[ProfileFloat], &DeviceProfileRandomFloatGenerator) + _ = json.Unmarshal(profiles[ProfileFloat], &DuplicateDeviceProfileRandomFloatGenerator) + _ = json.Unmarshal(profiles[ProfileNew], &NewDeviceProfile) return nil } diff --git a/internal/mock/mock_eventclient.go b/internal/mock/mock_eventclient.go index 1b8dc52ac..bae321618 100644 --- a/internal/mock/mock_eventclient.go +++ b/internal/mock/mock_eventclient.go @@ -14,60 +14,62 @@ import ( type EventClientMock struct{} -func (EventClientMock) AddBytes(event []byte, ctx context.Context) (string, error) { +func (e EventClientMock) Events(_ context.Context) ([]contract.Event, error) { panic("implement me") } -func (EventClientMock) MarshalEvent(e contract.Event) ([]byte, error) { +func (e EventClientMock) Event(_ context.Context, _ string) (contract.Event, error) { panic("implement me") } -func (EventClientMock) Events(ctx context.Context) ([]contract.Event, error) { +func (e EventClientMock) EventCount(_ context.Context) (int, error) { panic("implement me") } -func (EventClientMock) Event(id string, ctx context.Context) (contract.Event, error) { +func (e EventClientMock) EventCountForDevice(_ context.Context, _ string) (int, error) { panic("implement me") } -func (EventClientMock) EventCount(ctx context.Context) (int, error) { +func (e EventClientMock) EventsForDevice(_ context.Context, _ string, _ int) ([]contract.Event, error) { panic("implement me") } -func (EventClientMock) EventCountForDevice(deviceId string, ctx context.Context) (int, error) { +func (e EventClientMock) EventsForInterval(_ context.Context, _ int, _ int, _ int) ([]contract.Event, error) { panic("implement me") } -func (EventClientMock) EventsForDevice(id string, limit int, ctx context.Context) ([]contract.Event, error) { +func (e EventClientMock) EventsForDeviceAndValueDescriptor(_ context.Context, _ string, _ string, _ int) ([]contract.Event, error) { panic("implement me") } -func (EventClientMock) EventsForInterval(start int, end int, limit int, ctx context.Context) ([]contract.Event, error) { +func (e EventClientMock) Add(_ context.Context, _ *contract.Event) (string, error) { panic("implement me") } -func (EventClientMock) EventsForDeviceAndValueDescriptor(deviceId string, vd string, limit int, ctx context.Context) ([]contract.Event, error) { +func (e EventClientMock) AddBytes(_ context.Context, _ []byte) (string, error) { panic("implement me") } -func (EventClientMock) Add(event *contract.Event, ctx context.Context) (string, error) { - return "", nil +func (e EventClientMock) DeleteForDevice(_ context.Context, _ string) error { + panic("implement me") } -func (EventClientMock) DeleteForDevice(id string, ctx context.Context) error { +func (e EventClientMock) DeleteOld(_ context.Context, _ int) error { panic("implement me") } -func (EventClientMock) DeleteOld(age int, ctx context.Context) error { +func (e EventClientMock) Delete(_ context.Context, _ string) error { panic("implement me") } -func (EventClientMock) Delete(id string, ctx context.Context) error { +func (e EventClientMock) MarkPushed(_ context.Context, _ string) error { panic("implement me") } -func (EventClientMock) MarkPushed(id string, ctx context.Context) error { + +func (e EventClientMock) MarkPushedByChecksum(_ context.Context, _ string) error { panic("implement me") } -func (EventClientMock) MarkPushedByChecksum(id string, ctx context.Context) error { + +func (e EventClientMock) MarshalEvent(_ contract.Event) ([]byte, error) { panic("implement me") } diff --git a/internal/mock/mock_provisionwatcherclient.go b/internal/mock/mock_provisionwatcherclient.go index 4e1b71754..c55177b54 100644 --- a/internal/mock/mock_provisionwatcherclient.go +++ b/internal/mock/mock_provisionwatcherclient.go @@ -12,9 +12,6 @@ import ( "path/filepath" "runtime" - //"path/filepath" - //"runtime" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" ) @@ -31,27 +28,27 @@ type ProvisionWatcherClientMock struct { } // Get the provision watcher by id -func (ProvisionWatcherClientMock) ProvisionWatcher(id string, ctx context.Context) (contract.ProvisionWatcher, error) { +func (ProvisionWatcherClientMock) ProvisionWatcher(_ context.Context, _ string) (contract.ProvisionWatcher, error) { panic("implement me") } // Get a list of all provision watchers -func (ProvisionWatcherClientMock) ProvisionWatchers(ctx context.Context) ([]contract.ProvisionWatcher, error) { +func (ProvisionWatcherClientMock) ProvisionWatchers(_ context.Context) ([]contract.ProvisionWatcher, error) { panic("implement me") } // Get the provision watcher by name -func (ProvisionWatcherClientMock) ProvisionWatcherForName(name string, ctx context.Context) (contract.ProvisionWatcher, error) { +func (ProvisionWatcherClientMock) ProvisionWatcherForName(_ context.Context, _ string) (contract.ProvisionWatcher, error) { panic("implement me") } // Get the provision watchers that are on a service -func (ProvisionWatcherClientMock) ProvisionWatchersForService(serviceId string, ctx context.Context) ([]contract.ProvisionWatcher, error) { +func (ProvisionWatcherClientMock) ProvisionWatchersForService(_ context.Context, _ string) ([]contract.ProvisionWatcher, error) { panic("implement me") } // Get the provision watchers that are on a service(by name) -func (ProvisionWatcherClientMock) ProvisionWatchersForServiceByName(serviceName string, ctx context.Context) ([]contract.ProvisionWatcher, error) { +func (ProvisionWatcherClientMock) ProvisionWatchersForServiceByName(_ context.Context, _ string) ([]contract.ProvisionWatcher, error) { err := populateProvisionWatcherMock() if err != nil { return nil, err @@ -65,27 +62,27 @@ func (ProvisionWatcherClientMock) ProvisionWatchersForServiceByName(serviceName } // Get the provision watchers for a profile -func (ProvisionWatcherClientMock) ProvisionWatchersForProfile(profileId string, ctx context.Context) ([]contract.ProvisionWatcher, error) { +func (ProvisionWatcherClientMock) ProvisionWatchersForProfile(_ context.Context, _ string) ([]contract.ProvisionWatcher, error) { panic("implement me") } // Get the provision watchers for a profile (by name) -func (ProvisionWatcherClientMock) ProvisionWatchersForProfileByName(profileName string, ctx context.Context) ([]contract.ProvisionWatcher, error) { +func (ProvisionWatcherClientMock) ProvisionWatchersForProfileByName(_ context.Context, _ string) ([]contract.ProvisionWatcher, error) { panic("implement me") } // Add a provision watcher - handle error codes -func (ProvisionWatcherClientMock) Add(dev *contract.ProvisionWatcher, ctx context.Context) (string, error) { +func (ProvisionWatcherClientMock) Add(_ context.Context, _ *contract.ProvisionWatcher) (string, error) { panic("implement me") } // Update a provision watcher - handle error codes -func (ProvisionWatcherClientMock) Update(dev contract.ProvisionWatcher, ctx context.Context) error { +func (ProvisionWatcherClientMock) Update(_ context.Context, _ contract.ProvisionWatcher) error { panic("implement me") } // Delete a provision watcher (specified by id) -func (ProvisionWatcherClientMock) Delete(id string, ctx context.Context) error { +func (ProvisionWatcherClientMock) Delete(_ context.Context, _ string) error { panic("implement me") } @@ -97,12 +94,12 @@ func populateProvisionWatcherMock() error { return err } - json.Unmarshal(watchers[WatcherBool], &ValidBooleanWatcher) - json.Unmarshal(watchers[WatcherInt], &ValidIntegerWatcher) - json.Unmarshal(watchers[WatcherUint], &ValidUnsignedIntegerWatcher) - json.Unmarshal(watchers[WatcherFloat], &ValidFloatWatcher) - json.Unmarshal(watchers[WatcherFloat], &DuplicateFloatWatcher) - json.Unmarshal(watchers[WatcherNew], &NewProvisionWatcher) + _ = json.Unmarshal(watchers[WatcherBool], &ValidBooleanWatcher) + _ = json.Unmarshal(watchers[WatcherInt], &ValidIntegerWatcher) + _ = json.Unmarshal(watchers[WatcherUint], &ValidUnsignedIntegerWatcher) + _ = json.Unmarshal(watchers[WatcherFloat], &ValidFloatWatcher) + _ = json.Unmarshal(watchers[WatcherFloat], &DuplicateFloatWatcher) + _ = json.Unmarshal(watchers[WatcherNew], &NewProvisionWatcher) return nil } diff --git a/internal/mock/mock_valuedescriptorclient.go b/internal/mock/mock_valuedescriptorclient.go index 7419c9e3d..fd02de262 100644 --- a/internal/mock/mock_valuedescriptorclient.go +++ b/internal/mock/mock_valuedescriptorclient.go @@ -12,9 +12,10 @@ import ( "path/filepath" "runtime" - "github.com/edgexfoundry/device-sdk-go/internal/common" contract "github.com/edgexfoundry/go-mod-core-contracts/models" "github.com/google/uuid" + + "github.com/edgexfoundry/device-sdk-go/internal/common" ) var ( @@ -30,19 +31,18 @@ var ( ValueDescriptorUint64 = contract.ValueDescriptor{} ValueDescriptorFloat32 = contract.ValueDescriptor{} ValueDescriptorFloat64 = contract.ValueDescriptor{} - //ValueDescriptorString = contract.ValueDescriptor{} - NewValueDescriptor = contract.ValueDescriptor{} - DuplicateValueDescriptorInt16 = contract.ValueDescriptor{} - descMap = make(map[string]contract.ValueDescriptor, 0) + NewValueDescriptor = contract.ValueDescriptor{} + DuplicateValueDescriptorInt16 = contract.ValueDescriptor{} + descMap = make(map[string]contract.ValueDescriptor, 0) ) type ValueDescriptorMock struct{} -func (ValueDescriptorMock) ValueDescriptorsUsage(names []string, ctx context.Context) (map[string]bool, error) { +func (ValueDescriptorMock) ValueDescriptorsUsage(_ context.Context, _ []string) (map[string]bool, error) { panic("implement me") } -func (ValueDescriptorMock) ValueDescriptors(ctx context.Context) ([]contract.ValueDescriptor, error) { +func (ValueDescriptorMock) ValueDescriptors(_ context.Context) ([]contract.ValueDescriptor, error) { err := populateValueDescriptorMock() if err != nil { return nil, err @@ -60,47 +60,46 @@ func (ValueDescriptorMock) ValueDescriptors(ctx context.Context) ([]contract.Val ValueDescriptorUint64, ValueDescriptorFloat32, ValueDescriptorFloat64, - //ValueDescriptorString, }, nil } -func (ValueDescriptorMock) ValueDescriptor(id string, ctx context.Context) (contract.ValueDescriptor, error) { +func (ValueDescriptorMock) ValueDescriptor(_ context.Context, _ string) (contract.ValueDescriptor, error) { panic("implement me") } -func (ValueDescriptorMock) ValueDescriptorForName(name string, ctx context.Context) (contract.ValueDescriptor, error) { +func (ValueDescriptorMock) ValueDescriptorForName(_ context.Context, _ string) (contract.ValueDescriptor, error) { panic("implement me") } -func (ValueDescriptorMock) ValueDescriptorsByLabel(label string, ctx context.Context) ([]contract.ValueDescriptor, error) { +func (ValueDescriptorMock) ValueDescriptorsByLabel(_ context.Context, _ string) ([]contract.ValueDescriptor, error) { panic("implement me") } -func (ValueDescriptorMock) ValueDescriptorsForDevice(deviceId string, ctx context.Context) ([]contract.ValueDescriptor, error) { +func (ValueDescriptorMock) ValueDescriptorsForDevice(_ context.Context, _ string) ([]contract.ValueDescriptor, error) { panic("implement me") } -func (ValueDescriptorMock) ValueDescriptorsForDeviceByName(deviceName string, ctx context.Context) ([]contract.ValueDescriptor, error) { +func (ValueDescriptorMock) ValueDescriptorsForDeviceByName(_ context.Context, _ string) ([]contract.ValueDescriptor, error) { panic("implement me") } -func (ValueDescriptorMock) ValueDescriptorsByUomLabel(uomLabel string, ctx context.Context) ([]contract.ValueDescriptor, error) { +func (ValueDescriptorMock) ValueDescriptorsByUomLabel(_ context.Context, _ string) ([]contract.ValueDescriptor, error) { panic("implement me") } -func (ValueDescriptorMock) Add(vdr *contract.ValueDescriptor, ctx context.Context) (string, error) { +func (ValueDescriptorMock) Add(_ context.Context, _ *contract.ValueDescriptor) (string, error) { panic("implement me") } -func (ValueDescriptorMock) Update(vdr *contract.ValueDescriptor, ctx context.Context) error { +func (ValueDescriptorMock) Update(_ context.Context, _ *contract.ValueDescriptor) error { panic("implement me") } -func (ValueDescriptorMock) Delete(id string, ctx context.Context) error { +func (ValueDescriptorMock) Delete(_ context.Context, _ string) error { panic("implement me") } -func (ValueDescriptorMock) DeleteByName(name string, ctx context.Context) error { +func (ValueDescriptorMock) DeleteByName(_ context.Context, _ string) error { panic("implement me") } @@ -115,7 +114,7 @@ func populateValueDescriptorMock() error { if err != nil { return err } - json.Unmarshal(profiles["New-Device"], &NewDeviceProfile) + _ = json.Unmarshal(profiles["New-Device"], &NewDeviceProfile) dps = append(dps, NewDeviceProfile) for _, dp := range dps { diff --git a/internal/provision/devices.go b/internal/provision/devices.go index 1214f0363..c447aeb2e 100644 --- a/internal/provision/devices.go +++ b/internal/provision/devices.go @@ -59,7 +59,7 @@ func createDevice(dc common.DeviceConfig) error { device.Description = dc.Description common.LoggingClient.Debug(fmt.Sprintf("Adding Device: %v", device)) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - id, err := common.DeviceClient.Add(device, ctx) + id, err := common.DeviceClient.Add(ctx, device) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Add Device failed %s, error: %v", device.Name, err)) return err diff --git a/internal/provision/profiles.go b/internal/provision/profiles.go index 1bded7ca6..31a527962 100644 --- a/internal/provision/profiles.go +++ b/internal/provision/profiles.go @@ -77,13 +77,13 @@ func LoadProfiles(path string) error { // if profile already exists in metadata, skip it if p, ok := pMap[profile.Name]; ok { - cache.Profiles().Add(p) + _ = cache.Profiles().Add(p) continue } // add profile to metadata ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - id, err := common.DeviceProfileClient.Add(&profile, ctx) + id, err := common.DeviceProfileClient.Add(ctx, &profile) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Add Device Profile: %s to Core Metadata failed: %v", fullPath, err)) continue @@ -197,7 +197,7 @@ func createDescriptorFromResourceOperation(profileName string, op contract.Resou if err != nil { common.LoggingClient.Error(fmt.Sprintf("createing Value Descriptor %v failed: %v", desc, err)) } else { - cache.ValueDescriptors().Add(*desc) + _ = cache.ValueDescriptors().Add(*desc) } } } @@ -222,7 +222,7 @@ func createDescriptor(name string, dr contract.DeviceResource) (*contract.ValueD } ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - id, err := common.ValueDescriptorClient.Add(desc, ctx) + id, err := common.ValueDescriptorClient.Add(ctx, desc) if err != nil { return nil, err } diff --git a/internal/transformer/transformresult.go b/internal/transformer/transformresult.go index d59d76e0c..9cf779083 100644 --- a/internal/transformer/transformresult.go +++ b/internal/transformer/transformresult.go @@ -601,7 +601,7 @@ func CheckAssertion(cv *dsModels.CommandValue, assertion string, device *contrac device.OperatingState = contract.Disabled cache.Devices().Update(*device) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - go common.DeviceClient.UpdateOpStateByName(device.Name, contract.Disabled, ctx) + go common.DeviceClient.UpdateOpStateByName(ctx, device.Name, contract.Disabled) msg := fmt.Sprintf("assertion (%s) failed with value: %s", assertion, cv.ValueToString()) common.LoggingClient.Error(msg) return fmt.Errorf(msg) diff --git a/internal/urlclient/factory.go b/internal/urlclient/factory.go new file mode 100644 index 000000000..471a0f265 --- /dev/null +++ b/internal/urlclient/factory.go @@ -0,0 +1,93 @@ +/******************************************************************************* + * Copyright 2020 Dell Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + *******************************************************************************/ + +// urlclient provides functions to integrate the client code in go-mod-core-contracts with application specific code +package urlclient + +import ( + "context" + "sync" + + bootstrapConfig "github.com/edgexfoundry/go-mod-bootstrap/config" + "github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces" + "github.com/edgexfoundry/go-mod-core-contracts/clients/urlclient/local" + "github.com/edgexfoundry/go-mod-core-contracts/clients/urlclient/retry" + "github.com/edgexfoundry/go-mod-registry/registry" + + "github.com/edgexfoundry/device-sdk-go/internal/common" + "github.com/edgexfoundry/device-sdk-go/internal/endpoint" +) + +// NewData returns a URLClient that connects to a service attached to data. +func NewData( + ctx context.Context, + registryClient registry.Client, + wg *sync.WaitGroup, + path string) interfaces.URLClient { + + return newClient( + ctx, + registryClient, + wg, + common.ClientData, + path, + common.CurrentConfig.Clients[common.ClientData], + ) +} + +// NewMetadata returns a URLClient that connects to a service attached to metadata. +func NewMetadata( + ctx context.Context, + registryClient registry.Client, + wg *sync.WaitGroup, + path string) interfaces.URLClient { + + return newClient( + ctx, + registryClient, + wg, + common.ClientMetadata, + path, + common.CurrentConfig.Clients[common.ClientMetadata], + ) +} + +// newClient is a factory function that uses pre-defined constants to reduce code duplication. +func newClient( + ctx context.Context, + registryClient registry.Client, + wg *sync.WaitGroup, + serviceKey string, + path string, + client bootstrapConfig.ClientInfo) interfaces.URLClient { + + interval := 15 + + if registryClient != nil { + return retry.New( + endpoint.New( + ctx, + wg, + registryClient, + serviceKey, + path, + interval, + ).Monitor(), + interval, // retry interval == interval because we don't need to check for an update before an update + interval*10, // this scalar multiplier was chosen because it seemed reasonable + ) + } + + return local.New(client.Url() + path) +} diff --git a/pkg/service/init.go b/pkg/service/init.go index f14c5c079..76dfc56af 100644 --- a/pkg/service/init.go +++ b/pkg/service/init.go @@ -49,7 +49,7 @@ func (b *Bootstrap) BootstrapHandler(ctx context.Context, wg *sync.WaitGroup, _ svc = newService(dic) - err := clients.InitDependencyClients() + err := clients.InitDependencyClients(ctx, wg) if err != nil { _, _ = fmt.Fprintf(os.Stderr, "error: %v\n", err) return false diff --git a/pkg/service/manageddevices.go b/pkg/service/manageddevices.go index 200283d72..b94f1673e 100644 --- a/pkg/service/manageddevices.go +++ b/pkg/service/manageddevices.go @@ -40,7 +40,7 @@ func (s *Service) AddDevice(device contract.Device) (id string, err error) { device.Profile = prf ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - id, err = common.DeviceClient.Add(&device, ctx) + id, err = common.DeviceClient.Add(ctx, &device) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Add Device failed %s, error: %v", device.Name, err)) return "", err @@ -81,7 +81,7 @@ func (s *Service) RemoveDevice(id string) error { common.LoggingClient.Debug(fmt.Sprintf("Removing managed Device: : %s\n", device.Name)) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - err := common.DeviceClient.Delete(id, ctx) + err := common.DeviceClient.Delete(ctx, id) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Delete Device %s from Core Metadata failed", id)) } @@ -101,7 +101,7 @@ func (s *Service) RemoveDeviceByName(name string) error { common.LoggingClient.Debug(fmt.Sprintf("Removing managed Device: : %s\n", device.Name)) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - err := common.DeviceClient.DeleteByName(name, ctx) + err := common.DeviceClient.DeleteByName(ctx, name) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Delete Device %s from Core Metadata failed", name)) } @@ -121,7 +121,7 @@ func (s *Service) UpdateDevice(device contract.Device) error { common.LoggingClient.Debug(fmt.Sprintf("Updating managed Device: : %s\n", device.Name)) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - err := common.DeviceClient.Update(device, ctx) + err := common.DeviceClient.Update(ctx, device) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Update Device %s from Core Metadata failed: %v", device.Name, err)) } diff --git a/pkg/service/managedprofiles.go b/pkg/service/managedprofiles.go index f8dbabfce..629934612 100644 --- a/pkg/service/managedprofiles.go +++ b/pkg/service/managedprofiles.go @@ -31,7 +31,7 @@ func (s *Service) AddDeviceProfile(profile contract.DeviceProfile) (id string, e profile.Origin = millis ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - id, err = common.DeviceProfileClient.Add(&profile, ctx) + id, err = common.DeviceProfileClient.Add(ctx, &profile) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Add Profile failed %s, error: %v", profile.Name, err)) return "", err @@ -40,7 +40,7 @@ func (s *Service) AddDeviceProfile(profile contract.DeviceProfile) (id string, e return "", err } profile.Id = id - cache.Profiles().Add(profile) + _ = cache.Profiles().Add(profile) provision.CreateDescriptorsFromProfile(&profile) @@ -64,7 +64,7 @@ func (s *Service) RemoveDeviceProfile(id string) error { common.LoggingClient.Debug(fmt.Sprintf("Removing managed DeviceProfile: : %s", profile.Name)) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - err := common.DeviceProfileClient.Delete(id, ctx) + err := common.DeviceProfileClient.Delete(ctx, id) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Delete DeviceProfile %s from Core Metadata failed", id)) return err @@ -86,7 +86,7 @@ func (*Service) RemoveDeviceProfileByName(name string) error { common.LoggingClient.Debug(fmt.Sprintf("Removing managed DeviceProfile: : %s", profile.Name)) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - err := common.DeviceProfileClient.DeleteByName(name, ctx) + err := common.DeviceProfileClient.DeleteByName(ctx, name) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Delete DeviceProfile %s from Core Metadata failed", name)) return err @@ -108,7 +108,7 @@ func (*Service) UpdateDeviceProfile(profile contract.DeviceProfile) error { common.LoggingClient.Debug(fmt.Sprintf("Updating managed DeviceProfile: : %s", profile.Name)) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - err := common.DeviceProfileClient.Update(profile, ctx) + err := common.DeviceProfileClient.Update(ctx, profile) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Update DeviceProfile %s from Core Metadata failed: %v", profile.Name, err)) return err @@ -138,7 +138,7 @@ func (*Service) ResourceOperation(deviceName string, deviceResource string, meth // DeviceResource retrieves the specific DeviceResource instance from cache according to // the Device name and Device Resource name -func (*Service) DeviceResource(deviceName string, deviceResource string, method string) (contract.DeviceResource, bool) { +func (*Service) DeviceResource(deviceName string, deviceResource string, _ string) (contract.DeviceResource, bool) { device, ok := cache.Devices().ForName(deviceName) if !ok { common.LoggingClient.Error(fmt.Sprintf("retrieving DeviceResource - Device %s not found", deviceName)) diff --git a/pkg/service/managedwatchers.go b/pkg/service/managedwatchers.go index eb2245332..59e103ac1 100644 --- a/pkg/service/managedwatchers.go +++ b/pkg/service/managedwatchers.go @@ -39,7 +39,7 @@ func (s *Service) AddProvisionWatcher(watcher contract.ProvisionWatcher) (id str watcher.Profile = prf ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - id, err = common.ProvisionWatcherClient.Add(&watcher, ctx) + id, err = common.ProvisionWatcherClient.Add(ctx, &watcher) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Add Watcher failed %s, error: %v", watcher.Name, err)) return "", err @@ -48,6 +48,7 @@ func (s *Service) AddProvisionWatcher(watcher contract.ProvisionWatcher) (id str return "", err } watcher.Id = id + _ = cache.ProvisionWatchers().Add(watcher) return id, nil } @@ -80,7 +81,7 @@ func (s *Service) RemoveProvisionWatcher(id string) error { common.LoggingClient.Debug(fmt.Sprintf("Removing managed ProvisionWatcher: %s", pw.Name)) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - err := common.ProvisionWatcherClient.Delete(id, ctx) + err := common.ProvisionWatcherClient.Delete(ctx, id) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Delete ProvisionWatcher %s from Core Metadata failed", id)) return err @@ -101,7 +102,7 @@ func (s *Service) UpdateProvisionWatcher(watcher contract.ProvisionWatcher) erro common.LoggingClient.Debug(fmt.Sprintf("Updating managed ProvisionWatcher: %s", watcher.Name)) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - err := common.ProvisionWatcherClient.Update(watcher, ctx) + err := common.ProvisionWatcherClient.Update(ctx, watcher) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Update ProvisionWatcher %s from Core Metadata failed: %v", watcher.Name, err)) return err diff --git a/pkg/service/service.go b/pkg/service/service.go index 70aa96d77..de50a8134 100644 --- a/pkg/service/service.go +++ b/pkg/service/service.go @@ -72,7 +72,7 @@ func selfRegister() error { common.LoggingClient.Debug("Trying to find Device Service: " + common.ServiceName) ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - ds, err := common.DeviceServiceClient.DeviceServiceForName(common.ServiceName, ctx) + ds, err := common.DeviceServiceClient.DeviceServiceForName(ctx, common.ServiceName) if err != nil { if errsc, ok := err.(types.ErrServiceClient); ok && (errsc.StatusCode == http.StatusNotFound) { @@ -110,7 +110,7 @@ func createNewDeviceService() (contract.DeviceService, error) { ds.Origin = millis ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - id, err := common.DeviceServiceClient.Add(&ds, ctx) + id, err := common.DeviceServiceClient.Add(ctx, &ds) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Add Deviceservice: %s; failed: %v", common.ServiceName, err)) return contract.DeviceService{}, err @@ -130,7 +130,7 @@ func createNewDeviceService() (contract.DeviceService, error) { func makeNewAddressable() (*contract.Addressable, error) { // check whether there has been an existing addressable ctx := context.WithValue(context.Background(), common.CorrelationHeader, uuid.New().String()) - addr, err := common.AddressableClient.AddressableForName(common.ServiceName, ctx) + addr, err := common.AddressableClient.AddressableForName(ctx, common.ServiceName) if err != nil { if errsc, ok := err.(types.ErrServiceClient); ok && (errsc.StatusCode == http.StatusNotFound) { common.LoggingClient.Info(fmt.Sprintf("Addressable %s doesn't exist, creating a new one", common.ServiceName)) @@ -146,7 +146,7 @@ func makeNewAddressable() (*contract.Addressable, error) { Port: svc.svcInfo.Port, Path: common.APICallbackRoute, } - id, err := common.AddressableClient.Add(&addr, ctx) + id, err := common.AddressableClient.Add(ctx, &addr) if err != nil { common.LoggingClient.Error(fmt.Sprintf("Add addressable failed %s, error: %v", addr.Name, err)) return nil, err