From eb06a9b55426950d4c12d22c369b62e78365d325 Mon Sep 17 00:00:00 2001 From: Lenny Goodell Date: Wed, 16 Dec 2020 13:48:48 -0700 Subject: [PATCH] feat: Remove deprecated Mongo code. Mongo DB is no longer a feature. closes #2598 Signed-off-by: Lenny Goodell --- README.md | 4 +- bin/edgex-docker-launch.sh | 5 +- bin/edgex-launch.sh | 2 +- cmd/core-command/Attribution.txt | 3 - cmd/core-data/Attribution.txt | 3 - cmd/core-metadata/Attribution.txt | 3 - cmd/secrets-config/Attribution.txt | 3 - cmd/security-bootstrap-redis/Attribution.txt | 3 - .../Attribution.txt | 3 - cmd/security-proxy-setup/Attribution.txt | 3 - cmd/security-secrets-setup/Attribution.txt | 3 - .../Attribution.txt | 3 - cmd/support-notifications/Attribution.txt | 3 - cmd/support-scheduler/Attribution.txt | 3 - cmd/sys-mgmt-agent/Attribution.txt | 3 - cmd/sys-mgmt-executor/Attribution.txt | 3 - go.mod | 1 - internal/core/data/device_test.go | 10 +- internal/core/data/event_test.go | 10 +- internal/core/data/mocks/device.go | 3 +- .../data/v2/application/mocks/deviceClient.go | 3 +- internal/core/data/v2/mocks/device.go | 3 +- .../bootstrap/handlers/database/database.go | 12 - internal/pkg/db/db.go | 4 - internal/pkg/db/mongo/client.go | 112 -- internal/pkg/db/mongo/client_test.go | 90 -- internal/pkg/db/mongo/data.go | 695 ----------- internal/pkg/db/mongo/id.go | 48 - internal/pkg/db/mongo/metadata.go | 1087 ----------------- internal/pkg/db/mongo/models/addressable.go | 110 -- internal/pkg/db/mongo/models/channel.go | 39 - internal/pkg/db/mongo/models/command.go | 171 --- internal/pkg/db/mongo/models/device.go | 164 --- internal/pkg/db/mongo/models/deviceprofile.go | 309 ----- internal/pkg/db/mongo/models/devicereport.go | 81 -- internal/pkg/db/mongo/models/deviceservice.go | 120 -- internal/pkg/db/mongo/models/event.go | 103 -- internal/pkg/db/mongo/models/id.go | 50 - internal/pkg/db/mongo/models/interval.go | 85 -- .../pkg/db/mongo/models/interval_action.go | 95 -- internal/pkg/db/mongo/models/notification.go | 97 -- .../pkg/db/mongo/models/provisionwatcher.go | 128 -- internal/pkg/db/mongo/models/reading.go | 96 -- internal/pkg/db/mongo/models/subscription.go | 97 -- internal/pkg/db/mongo/models/transmission.go | 110 -- .../pkg/db/mongo/models/value_descriptor.go | 104 -- internal/pkg/db/mongo/notifications.go | 482 -------- internal/pkg/db/mongo/scheduler.go | 365 ------ internal/pkg/db/redis/CONFIGURATION.md | 5 +- internal/security/secretstore/init.go | 3 - .../support/notifications/enums/database.go | 54 - .../notifications/enums/database_test.go | 62 - .../support/notifications/interfaces/db.go | 25 - 53 files changed, 19 insertions(+), 5064 deletions(-) delete mode 100644 internal/pkg/db/mongo/client.go delete mode 100644 internal/pkg/db/mongo/client_test.go delete mode 100644 internal/pkg/db/mongo/data.go delete mode 100644 internal/pkg/db/mongo/id.go delete mode 100644 internal/pkg/db/mongo/metadata.go delete mode 100644 internal/pkg/db/mongo/models/addressable.go delete mode 100644 internal/pkg/db/mongo/models/channel.go delete mode 100644 internal/pkg/db/mongo/models/command.go delete mode 100644 internal/pkg/db/mongo/models/device.go delete mode 100644 internal/pkg/db/mongo/models/deviceprofile.go delete mode 100644 internal/pkg/db/mongo/models/devicereport.go delete mode 100644 internal/pkg/db/mongo/models/deviceservice.go delete mode 100644 internal/pkg/db/mongo/models/event.go delete mode 100644 internal/pkg/db/mongo/models/id.go delete mode 100644 internal/pkg/db/mongo/models/interval.go delete mode 100644 internal/pkg/db/mongo/models/interval_action.go delete mode 100644 internal/pkg/db/mongo/models/notification.go delete mode 100644 internal/pkg/db/mongo/models/provisionwatcher.go delete mode 100644 internal/pkg/db/mongo/models/reading.go delete mode 100644 internal/pkg/db/mongo/models/subscription.go delete mode 100644 internal/pkg/db/mongo/models/transmission.go delete mode 100644 internal/pkg/db/mongo/models/value_descriptor.go delete mode 100644 internal/pkg/db/mongo/notifications.go delete mode 100644 internal/pkg/db/mongo/scheduler.go delete mode 100644 internal/support/notifications/enums/database.go delete mode 100644 internal/support/notifications/enums/database_test.go diff --git a/README.md b/README.md index 0df398d76d..4fae4e40c3 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ cd bin ./edge-launch.sh ``` -**Note** You must have a database (Mongo or Redis) running before the services will operate +**Note** You must have a database (Redis) running before the services will operate correctly. If you don't want to install a database locally, you can host one via Docker. You may also need to change the `configuration.toml` files for one or more of the services. @@ -142,7 +142,7 @@ Follow the "Installation and Execution" steps above for obtaining and building t make docker run_docker ``` -**Note** The default behavior is to use Redis for the database, use the command `make EDGEX_DB=mongo run_docker` to start EdgeX with Mongo. +**Note** The default behavior is to use Redis for the database. ## Community diff --git a/bin/edgex-docker-launch.sh b/bin/edgex-docker-launch.sh index 8ff3f4400c..d9d2b50314 100755 --- a/bin/edgex-docker-launch.sh +++ b/bin/edgex-docker-launch.sh @@ -12,10 +12,9 @@ # or implied. See the License for the specific language governing permissions and limitations under # the License. -# Usage: bin/edgex-docker-launch.sh [mongo] +# Usage: bin/edgex-docker-launch.sh # -# By default download the Redis based Docker Compose file and attempt to start EdgeX. If the mongo -# option is used, download the Mongo based Docker Compose file and attempt to start EdgeX. +# By default download the Redis based Docker Compose file and attempt to start EdgeX. # # To override the compose file entirely set the COMPOSE_FILE_PATH environment variable to the full # pathname of the compose file you want to use. diff --git a/bin/edgex-launch.sh b/bin/edgex-launch.sh index 8c2fca9b3e..fe9d4cae4e 100755 --- a/bin/edgex-launch.sh +++ b/bin/edgex-launch.sh @@ -9,7 +9,7 @@ ### # Launches all EdgeX Go binaries (must be previously built). # -# Expects that Consul and MongoDB are already installed and running. +# Expects that Consul and Redis are already installed and running. # ### diff --git a/cmd/core-command/Attribution.txt b/cmd/core-command/Attribution.txt index 9193259aba..470a963bcb 100644 --- a/cmd/core-command/Attribution.txt +++ b/cmd/core-command/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/core-data/Attribution.txt b/cmd/core-data/Attribution.txt index 592dbff0ef..9b89bcc7f5 100644 --- a/cmd/core-data/Attribution.txt +++ b/cmd/core-data/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) - https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/core-metadata/Attribution.txt b/cmd/core-metadata/Attribution.txt index 9f0076804f..9dd5e30c33 100644 --- a/cmd/core-metadata/Attribution.txt +++ b/cmd/core-metadata/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/secrets-config/Attribution.txt b/cmd/secrets-config/Attribution.txt index 3c631c3f3f..727ac3c1c6 100644 --- a/cmd/secrets-config/Attribution.txt +++ b/cmd/secrets-config/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) - https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/security-bootstrap-redis/Attribution.txt b/cmd/security-bootstrap-redis/Attribution.txt index 7785b51784..6113f3869c 100644 --- a/cmd/security-bootstrap-redis/Attribution.txt +++ b/cmd/security-bootstrap-redis/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) - https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/security-file-token-provider/Attribution.txt b/cmd/security-file-token-provider/Attribution.txt index 4937919102..3deb8b0842 100644 --- a/cmd/security-file-token-provider/Attribution.txt +++ b/cmd/security-file-token-provider/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) - https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/security-proxy-setup/Attribution.txt b/cmd/security-proxy-setup/Attribution.txt index 3c631c3f3f..727ac3c1c6 100644 --- a/cmd/security-proxy-setup/Attribution.txt +++ b/cmd/security-proxy-setup/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) - https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/security-secrets-setup/Attribution.txt b/cmd/security-secrets-setup/Attribution.txt index 4937919102..3deb8b0842 100644 --- a/cmd/security-secrets-setup/Attribution.txt +++ b/cmd/security-secrets-setup/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) - https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/security-secretstore-setup/Attribution.txt b/cmd/security-secretstore-setup/Attribution.txt index 4937919102..3deb8b0842 100644 --- a/cmd/security-secretstore-setup/Attribution.txt +++ b/cmd/security-secretstore-setup/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) - https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/support-notifications/Attribution.txt b/cmd/support-notifications/Attribution.txt index 18300d98cb..afee8c3d05 100644 --- a/cmd/support-notifications/Attribution.txt +++ b/cmd/support-notifications/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/support-scheduler/Attribution.txt b/cmd/support-scheduler/Attribution.txt index 073ead501a..ba1376f5d7 100644 --- a/cmd/support-scheduler/Attribution.txt +++ b/cmd/support-scheduler/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/sys-mgmt-agent/Attribution.txt b/cmd/sys-mgmt-agent/Attribution.txt index cb0f3d18f6..ad22240a3a 100644 --- a/cmd/sys-mgmt-agent/Attribution.txt +++ b/cmd/sys-mgmt-agent/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/cmd/sys-mgmt-executor/Attribution.txt b/cmd/sys-mgmt-executor/Attribution.txt index 9d382e24f1..1fa18082ad 100644 --- a/cmd/sys-mgmt-executor/Attribution.txt +++ b/cmd/sys-mgmt-executor/Attribution.txt @@ -6,9 +6,6 @@ https://github.com/pkg/errors/blob/master/LICENSE gorilla/mux (BSD-3) https://github.com/gorilla/mux https://github.com/gorilla/mux/blob/master/LICENSE -globalsign/mgo (unspecified) - https://github.com/globalsign/mgo -https://github.com/globalsign/mgo/blob/master/LICENSE - pebbe/zmq4 (BSD-2) https://github.com/pebbe/zmq4 https://github.com/pebbe/zmq4/blob/master/LICENSE.txt diff --git a/go.mod b/go.mod index 604ec58f32..9529d3998e 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,6 @@ require ( github.com/edgexfoundry/go-mod-registry v0.1.26 github.com/edgexfoundry/go-mod-secrets v0.0.26 github.com/fxamacker/cbor/v2 v2.2.0 - github.com/globalsign/mgo v0.0.0-20181015135952-eeefdecb41b8 github.com/gomodule/redigo v2.0.0+incompatible github.com/google/uuid v1.1.2 github.com/gorilla/mux v1.8.0 diff --git a/internal/core/data/device_test.go b/internal/core/data/device_test.go index f342881f3b..22f8c6f8a8 100644 --- a/internal/core/data/device_test.go +++ b/internal/core/data/device_test.go @@ -8,11 +8,10 @@ import ( "github.com/edgexfoundry/edgex-go/internal/core/data/config" "github.com/edgexfoundry/edgex-go/internal/pkg/db" + "github.com/google/uuid" "github.com/edgexfoundry/go-mod-core-contracts/clients/logger" contract "github.com/edgexfoundry/go-mod-core-contracts/models" - - "github.com/globalsign/mgo/bson" ) var testEvent contract.Event @@ -59,7 +58,9 @@ func reset() { func buildReadings() []contract.Reading { ticks := db.MakeTimestamp() - r1 := contract.Reading{Id: bson.NewObjectId().Hex(), + + id, _ := uuid.NewUUID() + r1 := contract.Reading{Id: id.String(), Name: "Temperature", Value: "45", Origin: testOrigin, @@ -68,7 +69,8 @@ func buildReadings() []contract.Reading { Pushed: ticks, Device: testDeviceName} - r2 := contract.Reading{Id: bson.NewObjectId().Hex(), + id, _ = uuid.NewUUID() + r2 := contract.Reading{Id: id.String(), Name: "Pressure", Value: "1.01325", Origin: testOrigin, diff --git a/internal/core/data/event_test.go b/internal/core/data/event_test.go index e6e3f4611e..70ce0cb912 100644 --- a/internal/core/data/event_test.go +++ b/internal/core/data/event_test.go @@ -27,13 +27,13 @@ import ( dataMocks "github.com/edgexfoundry/edgex-go/internal/core/data/mocks" correlation "github.com/edgexfoundry/edgex-go/internal/pkg/correlation/models" "github.com/edgexfoundry/edgex-go/internal/pkg/db" + "github.com/google/uuid" "github.com/edgexfoundry/go-mod-core-contracts/clients/logger" contract "github.com/edgexfoundry/go-mod-core-contracts/models" "github.com/edgexfoundry/go-mod-messaging/messaging" msgTypes "github.com/edgexfoundry/go-mod-messaging/pkg/types" - "github.com/globalsign/mgo/bson" "github.com/stretchr/testify/mock" ) @@ -275,7 +275,7 @@ func TestAddEventNoPersistence(t *testing.T) { wg.Add(1) go handleDomainEvents(bitEvents, chEvents, &wg, t) - newId, err := addNewEvent( + _, err := addNewEvent( correlation.Event{Event: evt}, context.Background(), logger.NewMockClient(), @@ -292,9 +292,6 @@ func TestAddEventNoPersistence(t *testing.T) { if err != nil { t.Errorf(err.Error()) } - if bson.IsObjectIdHex(newId) { - t.Errorf("unexpected bson id %s received", newId) - } wg.Wait() for i, val := range bitEvents { @@ -311,7 +308,8 @@ func TestUpdateEventNotFound(t *testing.T) { dbClientMock := &dbMock.DBClient{} dbClientMock.On("EventById", mock.Anything).Return(contract.Event{}, fmt.Errorf("Event not found")) - evt := contract.Event{ID: bson.NewObjectId().Hex(), Device: "Not Found", Origin: testOrigin} + id, _ := uuid.NewUUID() + evt := contract.Event{ID: id.String(), Device: "Not Found", Origin: testOrigin} err := updateEvent( correlation.Event{Event: evt}, context.Background(), diff --git a/internal/core/data/mocks/device.go b/internal/core/data/mocks/device.go index a98d660be5..d884c44cdb 100644 --- a/internal/core/data/mocks/device.go +++ b/internal/core/data/mocks/device.go @@ -22,7 +22,6 @@ import ( "github.com/edgexfoundry/go-mod-core-contracts/clients/types" contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" "github.com/google/uuid" "github.com/stretchr/testify/mock" @@ -38,7 +37,7 @@ func NewMockDeviceClient() *mocks.DeviceClient { protocols := getProtocols() mockDeviceResultFn := func(ctx context.Context, id string) contract.Device { - if bson.IsObjectIdHex(id) { + if len(id) > 0 { return contract.Device{Id: id, Name: testDeviceName, Protocols: protocols} } return contract.Device{} diff --git a/internal/core/data/v2/application/mocks/deviceClient.go b/internal/core/data/v2/application/mocks/deviceClient.go index f6486c47ca..3d46a28b9d 100644 --- a/internal/core/data/v2/application/mocks/deviceClient.go +++ b/internal/core/data/v2/application/mocks/deviceClient.go @@ -15,7 +15,6 @@ import ( "github.com/edgexfoundry/go-mod-core-contracts/clients/types" contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" "github.com/google/uuid" "github.com/stretchr/testify/mock" ) @@ -30,7 +29,7 @@ func NewMockDeviceClient() *mocks.DeviceClient { protocols := getProtocols() mockDeviceResultFn := func(ctx context.Context, id string) contract.Device { - if bson.IsObjectIdHex(id) { + if len(id) > 0 { return contract.Device{Id: id, Name: testDeviceName, Protocols: protocols} } return contract.Device{} diff --git a/internal/core/data/v2/mocks/device.go b/internal/core/data/v2/mocks/device.go index 9e194a1b57..ee21b7503b 100644 --- a/internal/core/data/v2/mocks/device.go +++ b/internal/core/data/v2/mocks/device.go @@ -18,7 +18,6 @@ import ( "github.com/edgexfoundry/go-mod-core-contracts/clients/types" contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" "github.com/google/uuid" "github.com/stretchr/testify/mock" ) @@ -32,7 +31,7 @@ func NewMockDeviceClient() *mocks.DeviceClient { protocols := getProtocols() mockDeviceResultFn := func(ctx context.Context, id string) contract.Device { - if bson.IsObjectIdHex(id) { + if len(id) > 0 { return contract.Device{Id: id, Name: testDeviceName, Protocols: protocols} } return contract.Device{} diff --git a/internal/pkg/bootstrap/handlers/database/database.go b/internal/pkg/bootstrap/handlers/database/database.go index 471ed3694d..863e678431 100644 --- a/internal/pkg/bootstrap/handlers/database/database.go +++ b/internal/pkg/bootstrap/handlers/database/database.go @@ -24,7 +24,6 @@ import ( "github.com/edgexfoundry/edgex-go/internal/pkg/bootstrap/interfaces" "github.com/edgexfoundry/edgex-go/internal/pkg/db" dbInterfaces "github.com/edgexfoundry/edgex-go/internal/pkg/db/interfaces" - "github.com/edgexfoundry/edgex-go/internal/pkg/db/mongo" "github.com/edgexfoundry/edgex-go/internal/pkg/db/redis" bootstrapContainer "github.com/edgexfoundry/go-mod-bootstrap/bootstrap/container" @@ -72,17 +71,6 @@ func (d Database) newDBClient( databaseInfo := d.database.GetDatabaseInfo()["Primary"] switch databaseInfo.Type { - // Deprecated: Mongo functionality is deprecated as of the Geneva release. - case db.MongoDB: - return mongo.NewClient( - db.Configuration{ - Host: databaseInfo.Host, - Port: databaseInfo.Port, - Timeout: databaseInfo.Timeout, - DatabaseName: databaseInfo.Name, - Username: credentials.Username, - Password: credentials.Password, - }) case db.RedisDB: conf := db.Configuration{ Host: databaseInfo.Host, diff --git a/internal/pkg/db/db.go b/internal/pkg/db/db.go index 1940c575ab..04d60e694e 100644 --- a/internal/pkg/db/db.go +++ b/internal/pkg/db/db.go @@ -22,10 +22,6 @@ import ( const ( // Databases - // MongoDB the unique identifier used in configuring the system to signal the underlying database used is MongoDB. - // - // Deprecated: Mongo functionality is deprecated as of the Geneva release. - MongoDB = "mongodb" RedisDB = "redisdb" // Data diff --git a/internal/pkg/db/mongo/client.go b/internal/pkg/db/mongo/client.go deleted file mode 100644 index afd1e4962e..0000000000 --- a/internal/pkg/db/mongo/client.go +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * Copyright 2017 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. - *******************************************************************************/ - -// Package mongo provides an implementation of DBClient which uses MongoDB as the underlying data-store. -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release and no new functionality should be added; -// Only bugs which address legacy issues -package mongo - -import ( - "strconv" - "time" - - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - "github.com/globalsign/mgo" -) - -var currentMongoClient MongoClient // Singleton used so that mongoEvent can use it to de-reference readings - -// MongoClient implements DBClient and provides functionality for interacting with MongoDB. -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release and no new functionality should be added; -// Only bugs which address legacy issues -type MongoClient struct { - session *mgo.Session // Mongo database session - database *mgo.Database // Mongo database -} - -// Return a pointer to the MongoClient -// -// Deprecated: MongoClient is deprecated as of the Geneva release. -func NewClient(config db.Configuration) (MongoClient, error) { - m := MongoClient{} - - // Create the dial info for the Mongo session - connectionString := config.Host + ":" + strconv.Itoa(config.Port) - mongoDBDialInfo := &mgo.DialInfo{ - Addrs: []string{connectionString}, - Timeout: time.Duration(config.Timeout) * time.Millisecond, - Database: config.DatabaseName, - Username: config.Username, - Password: config.Password, - } - session, err := mgo.DialWithInfo(mongoDBDialInfo) - if err != nil { - return m, err - } - - m.session = session - m.database = session.DB(config.DatabaseName) - - currentMongoClient = m // Set the singleton - return m, nil -} - -func (mc MongoClient) CloseSession() { - if mc.session != nil { - mc.session.Close() - mc.session = nil - } -} - -// Get the current Mongo Client -func getCurrentMongoClient() (MongoClient, error) { - return currentMongoClient, nil -} - -// Get a copy of the session -func (mc MongoClient) getSessionCopy() *mgo.Session { - return mc.session.Copy() -} - -func errorMap(err error) error { - if err == mgo.ErrNotFound { - err = db.ErrNotFound - } - return err -} - -// Delete from the collection based on ID -func (mc MongoClient) deleteById(col string, id string) error { - s := mc.getSessionCopy() - defer s.Close() - - query, err := idToBsonM(id) - if err != nil { - return err - } - return errorMap(s.DB(mc.database.Name).C(col).Remove(query)) -} - -func (mc MongoClient) updateId(col string, id string, update interface{}) error { - s := mc.getSessionCopy() - defer s.Close() - - query, err := idToBsonM(id) - if err != nil { - return err - } - return errorMap(s.DB(mc.database.Name).C(col).Update(query, update)) -} diff --git a/internal/pkg/db/mongo/client_test.go b/internal/pkg/db/mongo/client_test.go deleted file mode 100644 index 3e73434ffa..0000000000 --- a/internal/pkg/db/mongo/client_test.go +++ /dev/null @@ -1,90 +0,0 @@ -// -// Copyright (c) 2018 Cavium -// -// SPDX-License-Identifier: Apache-2.0 -// - -// +build mongoRunning - -// This test will only be executed if the tag mongoRunning is added when running -// the tests with a command like: -// go test -tags mongoRunning - -// Package mongo provides integration tests for interaction with MongoDO. -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release and no new functionality should be added; -// Only bugs which address legacy issues -package mongo - -import ( - "testing" - - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - "github.com/edgexfoundry/edgex-go/internal/pkg/db/test" -) - -// TestMongoDB -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -func TestMongoDB(t *testing.T) { - - t.Log("This test needs to have a running mongo on localhost") - - config := db.Configuration{ - Host: "0.0.0.0", - Port: 27017, - DatabaseName: "coredata", - Timeout: 1000, - } - mongo, err := NewClient(config) - if err != nil { - t.Fatalf("Could not connect: %v", err) - } - test.TestDataDB(t, mongo) - - config.DatabaseName = "metadata" - mongo, err = NewClient(config) - if err != nil { - t.Fatalf("Could not connect: %v", err) - } - test.TestMetadataDB(t, mongo) - - config.DatabaseName = "export" - mongo, err = NewClient(config) - if err != nil { - t.Fatalf("Could not connect: %v", err) - } - test.TestExportDB(t, mongo) - - config.DatabaseName = "scheduler" - mongo, err = NewClient(config) - if err != nil { - t.Fatalf("Could not connect: %v", err) - } - test.TestSchedulerDB(t, mongo) -} - -// BenchmarkMongoDB -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -func BenchmarkMongoDB(b *testing.B) { - - b.Log("This benchmark needs to have a running mongo on localhost") - - config := db.Configuration{ - Host: "0.0.0.0", - Port: 27017, - DatabaseName: "coredata", - Timeout: 1000, - } - mongo, err := NewClient(config) - - if err != nil { - b.Fatalf("Could not connect with mongodb: %v", err) - } - - s := mongo.getSessionCopy() - defer s.Close() - - test.BenchmarkDB(b, mongo) -} diff --git a/internal/pkg/db/mongo/data.go b/internal/pkg/db/mongo/data.go deleted file mode 100644 index 0676e410f2..0000000000 --- a/internal/pkg/db/mongo/data.go +++ /dev/null @@ -1,695 +0,0 @@ -/******************************************************************************* - * Copyright 2017 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. - *******************************************************************************/ -package mongo - -import ( - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo" - "github.com/globalsign/mgo/bson" - - correlation "github.com/edgexfoundry/edgex-go/internal/pkg/correlation/models" - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - "github.com/edgexfoundry/edgex-go/internal/pkg/db/mongo/models" -) - -/* -Core data client -Has functions for interacting with the core data mongo database -*/ - -// ******************************* EVENTS ********************************** - -// Return all the events -// UnexpectedError - failed to retrieve events from the database -// Sort the events in descending order by ID -func (mc MongoClient) Events() ([]contract.Event, error) { - return mc.mapEvents(mc.getEvents(bson.M{})) - -} - -// Return events up to the max number specified -// UnexpectedError - failed to retrieve events from the database -// Sort the events in descending order by ID -func (mc MongoClient) EventsWithLimit(limit int) ([]contract.Event, error) { - return mc.mapEvents(mc.getEventsLimit(bson.M{}, limit)) -} - -// Add a new event -// UnexpectedError - failed to add to database -// NoValueDescriptor - no existing value descriptor for a reading in the event -func (mc MongoClient) AddEvent(e correlation.Event) (string, error) { - s := mc.getSessionCopy() - defer s.Close() - - if e.Created == 0 { - e.Created = db.MakeTimestamp() - } - - if e.Modified == 0 { - e.Modified = e.Created - } - - // Add the readings - if len(e.Readings) > 0 { - var ui []interface{} - for i, reading := range e.Readings { - var r models.Reading - id, err := r.FromContract(reading) - if err != nil { - return "", err - } - - r.Created = e.Created - r.Modified = e.Modified - - if reading.Device == "" { - r.Device = e.Device - } - - ui = append(ui, r) - - e.Readings[i].Id = id - } - if err := s.DB(mc.database.Name).C(db.ReadingsCollection).Insert(ui...); err != nil { - return "", errorMap(err) - } - } - - var mapped models.Event - id, err := mapped.FromContract(e, mc) - if err != nil { - return "", err - } - - if err = s.DB(mc.database.Name).C(db.EventsCollection).Insert(mapped); err != nil { - return "", errorMap(err) - } - return id, nil -} - -// Update an event - do NOT update readings -// UnexpectedError - problem updating in database -// NotFound - no event with the ID was found -func (mc MongoClient) UpdateEvent(e correlation.Event) error { - var mapped models.Event - id, err := mapped.FromContract(e, mc) - if err != nil { - return err - } - - mapped.TimestampForUpdate() - - return mc.updateId(db.EventsCollection, id, mapped) -} - -// Get an event by id -func (mc MongoClient) EventById(id string) (contract.Event, error) { - s := mc.getSessionCopy() - defer s.Close() - - query, err := idToBsonM(id) - if err != nil { - return contract.Event{}, err - } - - var evt models.Event - if err := s.DB(mc.database.Name).C(db.EventsCollection).Find(query).One(&evt); err != nil { - return contract.Event{}, errorMap(err) - } - return evt.ToContract(mc) -} - -// EventsByChecksum get events with matching checksum -func (mc MongoClient) EventsByChecksum(checksum string) ([]contract.Event, error) { - events, err := mc.mapEvents(mc.getEvents(bson.M{"checksum": checksum})) - - if err != nil { - return events, err - } - - if len(events) == 0 { - return events, db.ErrNotFound - } - - return events, nil -} - -// Get the number of events in Mongo -func (mc MongoClient) EventCount() (int, error) { - s := mc.getSessionCopy() - defer s.Close() - - count, err := s.DB(mc.database.Name).C(db.EventsCollection).Find(nil).Count() - if err != nil { - return 0, errorMap(err) - } - return count, nil -} - -// Get the number of events in Mongo for the device -func (mc MongoClient) EventCountByDeviceId(id string) (int, error) { - s := mc.getSessionCopy() - defer s.Close() - - query := bson.M{"device": id} - count, err := s.DB(mc.database.Name).C(db.EventsCollection).Find(query).Count() - if err != nil { - return 0, errorMap(err) - } - return count, nil -} - -// Delete an event by ID and all of its readings -// 404 - Event not found -// 503 - Unexpected problems -func (mc MongoClient) DeleteEventById(id string) error { - return mc.deleteById(db.EventsCollection, id) -} - -// DeleteEventsByDevice Delete events and readings associated with the specified device ID -func (mc MongoClient) DeleteEventsByDevice(deviceId string) (int, error) { - err := mc.DeleteReadingsByDevice(deviceId) - if err != nil { - return 0, err - } - - s := mc.getSessionCopy() - defer s.Close() - - i, err := s.DB(mc.database.Name).C(db.EventsCollection).RemoveAll(bson.M{"device": deviceId}) - if err != nil { - return 0, err - } - - return i.Removed, err -} - -// Get a list of events based on the device id and limit -func (mc MongoClient) EventsForDeviceLimit(id string, limit int) ([]contract.Event, error) { - return mc.mapEvents(mc.getEventsLimit(bson.M{"device": id}, limit)) -} - -// Get a list of events based on the device id -func (mc MongoClient) EventsForDevice(id string) ([]contract.Event, error) { - return mc.mapEvents(mc.getEvents(bson.M{"device": id})) -} - -// Return a list of events whose creation time is between startTime and endTime -// Limit the number of results by limit -func (mc MongoClient) EventsByCreationTime(startTime, endTime int64, limit int) ([]contract.Event, error) { - query := bson.M{"created": bson.M{ - "$gte": startTime, - "$lte": endTime, - }} - return mc.mapEvents(mc.getEventsLimit(query, limit)) -} - -// Get Events that are older than the given age (defined by age = now - created) -func (mc MongoClient) EventsOlderThanAge(age int64) ([]contract.Event, error) { - expireDate := (db.MakeTimestamp()) - age - return mc.mapEvents(mc.getEvents(bson.M{"created": bson.M{"$lt": expireDate}})) -} - -// Get all of the events that have been pushed -func (mc MongoClient) EventsPushed() ([]contract.Event, error) { - return mc.mapEvents(mc.getEvents(bson.M{"pushed": bson.M{"$gt": int64(0)}})) -} - -// Delete all of the readings and all of the events -func (mc MongoClient) ScrubAllEvents() error { - s := mc.getSessionCopy() - defer s.Close() - - _, err := s.DB(mc.database.Name).C(db.ReadingsCollection).RemoveAll(nil) - if err != nil { - return errorMap(err) - } - - _, err = s.DB(mc.database.Name).C(db.EventsCollection).RemoveAll(nil) - if err != nil { - return errorMap(err) - } - - return nil -} - -// Get events for the passed query -func (mc MongoClient) getEvents(q bson.M) (me []models.Event, err error) { - s := mc.getSessionCopy() - defer s.Close() - - err = s.DB(mc.database.Name).C(db.EventsCollection).Find(q).All(&me) - if err != nil { - return []models.Event{}, errorMap(err) - } - return -} - -// Get events with a limit -// Sort the list before applying the limit so we can return the most recent events -func (mc MongoClient) getEventsLimit(q bson.M, limit int) (me []models.Event, err error) { - s := mc.getSessionCopy() - defer s.Close() - - // Check if limit is 0 - if limit == 0 { - return []models.Event{}, nil - } - - err = s.DB(mc.database.Name).C(db.EventsCollection).Find(q).Sort("-modified").Limit(limit).All(&me) - if err != nil { - return []models.Event{}, errorMap(err) - } - return -} - -// ************************ READINGS ************************************8 - -func (mc MongoClient) DBRefToReading(dbRef mgo.DBRef) (a models.Reading, err error) { - if err = mc.database.C(db.ReadingsCollection).Find(bson.M{"_id": dbRef.Id}).One(&a); err != nil { - return models.Reading{}, errorMap(err) - } - return -} - -func (mc MongoClient) ReadingToDBRef(r models.Reading) (dbRef mgo.DBRef, err error) { - s := mc.session.Copy() - defer s.Close() - - // validate identity provided in contract actually exists and populate missing Id, Uuid field - var reading models.Reading - if r.Id.Valid() { - reading, err = mc.readingById(r.Id.Hex()) - } else { - reading, err = mc.readingById(r.Uuid) - } - if err != nil { - return dbRef, err - } - - dbRef = mgo.DBRef{Collection: db.ReadingsCollection, Id: reading.Id} - return -} - -// Return a list of readings sorted by reading id -func (mc MongoClient) Readings() ([]contract.Reading, error) { - readings, err := mc.getReadings(nil) - if err != nil { - return []contract.Reading{}, err - } - - mapped := make([]contract.Reading, 0) - for _, r := range readings { - mapped = append(mapped, r.ToContract()) - } - return mapped, nil -} - -// Post a new reading -func (mc MongoClient) AddReading(r contract.Reading) (string, error) { - s := mc.getSessionCopy() - defer s.Close() - - var mapped models.Reading - id, err := mapped.FromContract(r) - if err != nil { - return "", err - } - - mapped.TimestampForAdd() - - err = s.DB(mc.database.Name).C(db.ReadingsCollection).Insert(&mapped) - if err != nil { - return "", errorMap(err) - } - return id, err -} - -// Update a reading -// 404 - reading cannot be found -// 409 - Value descriptor doesn't exist -// 503 - unknown issues -func (mc MongoClient) UpdateReading(r contract.Reading) error { - var mapped models.Reading - id, err := mapped.FromContract(r) - if err != nil { - return err - } - - mapped.TimestampForUpdate() - - return mc.updateId(db.ReadingsCollection, id, mapped) -} - -// Get a reading by ID -func (mc MongoClient) ReadingById(id string) (contract.Reading, error) { - res, err := mc.readingById(id) - if err != nil { - return contract.Reading{}, err - } - return res.ToContract(), nil -} - -func (mc MongoClient) readingById(id string) (models.Reading, error) { - s := mc.getSessionCopy() - defer s.Close() - - query, err := idToBsonM(id) - if err != nil { - return models.Reading{}, err - } - - var res models.Reading - if err = s.DB(mc.database.Name).C(db.ReadingsCollection).Find(query).One(&res); err != nil { - return models.Reading{}, errorMap(err) - } - return res, nil -} - -// Get the count of readings in Mongo -func (mc MongoClient) ReadingCount() (int, error) { - s := mc.getSessionCopy() - defer s.Close() - - count, err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(bson.M{}).Count() - if err != nil { - return 0, errorMap(err) - } - return count, nil -} - -// Delete a reading by ID -// 404 - can't find the reading with the given id -func (mc MongoClient) DeleteReadingById(id string) error { - return mc.deleteById(db.ReadingsCollection, id) -} -func (mc MongoClient) DeleteReadingsByDevice(deviceId string) error { - s := mc.getSessionCopy() - defer s.Close() - - _, err := s.DB(mc.database.Name).C(db.ReadingsCollection).RemoveAll(bson.M{"device": deviceId}) - return err -} - -// Return a list of readings for the given device (id or name) -// Sort the list of readings on creation date -func (mc MongoClient) ReadingsByDevice(id string, limit int) ([]contract.Reading, error) { - return mapReadings(mc.getReadingsLimit(bson.M{"device": id}, limit)) -} - -// Return a list of readings for the given value descriptor -// Limit by the given limit -func (mc MongoClient) ReadingsByValueDescriptor(name string, limit int) ([]contract.Reading, error) { - return mapReadings(mc.getReadingsLimit(bson.M{"name": name}, limit)) -} - -// Return a list of readings whose name is in the list of value descriptor names -func (mc MongoClient) ReadingsByValueDescriptorNames(names []string, limit int) ([]contract.Reading, error) { - return mapReadings(mc.getReadingsLimit(bson.M{"name": bson.M{"$in": names}}, limit)) -} - -// Return a list of readings whose creation time is in-between start and end -// Limit by the limit parameter -func (mc MongoClient) ReadingsByCreationTime(start, end int64, limit int) ([]contract.Reading, error) { - return mapReadings(mc.getReadingsLimit(bson.M{"created": bson.M{"$gte": start, "$lte": end}}, limit)) -} - -// Return a list of readings for a device filtered by the value descriptor and limited by the limit -// The readings are linked to the device through an event -func (mc MongoClient) ReadingsByDeviceAndValueDescriptor(deviceId, valueDescriptor string, limit int) ([]contract.Reading, error) { - return mapReadings(mc.getReadingsLimit(bson.M{"device": deviceId, "name": valueDescriptor}, limit)) -} - -// Return a list of readings that match. -// Sort the list before applying the limit so we can return the most recent readings -func (mc MongoClient) getReadingsLimit(q bson.M, limit int) ([]models.Reading, error) { - s := mc.getSessionCopy() - defer s.Close() - - // Check if limit is 0 - if limit == 0 { - return []models.Reading{}, nil - } - - var readings []models.Reading - if err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(q).Sort("-modified").Limit(limit).All(&readings); err != nil { - return []models.Reading{}, errorMap(err) - } - return readings, nil -} - -// Get readings from the database -func (mc MongoClient) getReadings(q bson.M) ([]models.Reading, error) { - s := mc.getSessionCopy() - defer s.Close() - - var readings []models.Reading - if err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(q).Sort("-modified").All(&readings); err != nil { - return []models.Reading{}, errorMap(err) - } - return readings, nil -} - -// Get a reading from the database with the passed query -func (mc MongoClient) getReading(q bson.M) (models.Reading, error) { - s := mc.getSessionCopy() - defer s.Close() - - var res models.Reading - if err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(q).One(&res); err != nil { - return models.Reading{}, errorMap(err) - } - return res, nil -} - -// ************************* VALUE DESCRIPTORS ***************************** - -// Add a value descriptor -// 409 - Formatting is bad or it is not unique -// 503 - Unexpected -// TODO: Check for valid printf formatting -func (mc MongoClient) AddValueDescriptor(v contract.ValueDescriptor) (string, error) { - s := mc.getSessionCopy() - defer s.Close() - - var mapped models.ValueDescriptor - id, err := mapped.FromContract(v) - if err != nil { - return "", err - } - - // See if the name is unique and add the value descriptors - found, err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).Find(bson.M{"name": mapped.Name}).Count() - if err != nil { - return "", errorMap(err) - } - // Duplicate name - if found > 0 { - return "", db.ErrNotUnique - } - - mapped.Modified = db.MakeTimestamp() - mapped.Created = mapped.Modified - - if err = s.DB(mc.database.Name).C(db.ValueDescriptorCollection).Insert(mapped); err != nil { - return "", errorMap(err) - } - return id, nil -} - -// Return a list of all the value descriptors -// 513 Service Unavailable - database problems -func (mc MongoClient) ValueDescriptors() ([]contract.ValueDescriptor, error) { - return mapValueDescriptors(mc.getValueDescriptors(nil)) -} - -// Update a value descriptor -// First use the ID for identification, then the name -// TODO: Check for the valid printf formatting -// 404 not found if the value descriptor cannot be found by the identifiers -func (mc MongoClient) UpdateValueDescriptor(cvd contract.ValueDescriptor) error { - // See if the name is unique if it changed - chk, err := mc.getValueDescriptor(bson.M{"name": cvd.Name}) - if err != db.ErrNotFound { - if err != nil { - return err - } - - // IDs are different -> name not unique - if chk.Id.Hex() != cvd.Id && cvd.Id != chk.Uuid { - return db.ErrNotUnique - } - } - - var mapped models.ValueDescriptor - id, err := mapped.FromContract(cvd) - if err != nil { - return err - } - - mapped.Modified = db.MakeTimestamp() - - return mc.updateId(db.ValueDescriptorCollection, id, mapped) -} - -// Delete the value descriptor based on the id -// Not found error if there isn't a value descriptor for the ID -// ValueDescriptorStillInUse if the value descriptor is still referenced by readings -func (mc MongoClient) DeleteValueDescriptorById(id string) error { - return mc.deleteById(db.ValueDescriptorCollection, id) -} - -// Return a value descriptor based on the name -// Can return null if no value descriptor is found -func (mc MongoClient) ValueDescriptorByName(name string) (contract.ValueDescriptor, error) { - mvd, err := mc.getValueDescriptor(bson.M{"name": name}) - if err != nil { - return contract.ValueDescriptor{}, err - } - return mvd.ToContract(), nil -} - -// Return all of the value descriptors based on the names -func (mc MongoClient) ValueDescriptorsByName(names []string) ([]contract.ValueDescriptor, error) { - vList := make([]contract.ValueDescriptor, 0) - for _, name := range names { - v, err := mc.ValueDescriptorByName(name) - if err != nil && err != db.ErrNotFound { - return []contract.ValueDescriptor{}, err - } - if err == nil { - vList = append(vList, v) - } - } - - return vList, nil -} - -// Return a value descriptor based on the id -// Return NotFoundError if there is no value descriptor for the id -func (mc MongoClient) ValueDescriptorById(id string) (contract.ValueDescriptor, error) { - query, err := idToBsonM(id) - if err != nil { - return contract.ValueDescriptor{}, err - } - - mvd, err := mc.getValueDescriptor(query) - if err != nil { - return contract.ValueDescriptor{}, err - } - return mvd.ToContract(), nil -} - -// Return all the value descriptors that match the UOM label -func (mc MongoClient) ValueDescriptorsByUomLabel(uomLabel string) ([]contract.ValueDescriptor, error) { - return mapValueDescriptors(mc.getValueDescriptors(bson.M{"uomLabel": uomLabel})) -} - -// Return value descriptors based on if it has the label -func (mc MongoClient) ValueDescriptorsByLabel(label string) ([]contract.ValueDescriptor, error) { - return mapValueDescriptors(mc.getValueDescriptors(bson.M{"labels": label})) -} - -// Return value descriptors based on the type -func (mc MongoClient) ValueDescriptorsByType(t string) ([]contract.ValueDescriptor, error) { - return mapValueDescriptors(mc.getValueDescriptors(bson.M{"type": t})) -} - -// Delete all of the value descriptors -func (mc MongoClient) ScrubAllValueDescriptors() error { - s := mc.getSessionCopy() - defer s.Close() - - if _, err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).RemoveAll(nil); err != nil { - return errorMap(err) - } - return nil -} - -// Get value descriptors based on the query -func (mc MongoClient) getValueDescriptors(q bson.M) ([]models.ValueDescriptor, error) { - s := mc.getSessionCopy() - defer s.Close() - - var v []models.ValueDescriptor - if err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).Find(q).All(&v); err != nil { - return []models.ValueDescriptor{}, errorMap(err) - } - return v, nil -} - -// Get value descriptors with a limit based on the query -func (mc MongoClient) getValueDescriptorsLimit(q bson.M, limit int) ([]models.ValueDescriptor, error) { - s := mc.getSessionCopy() - defer s.Close() - - var v []models.ValueDescriptor - if err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).Find(q).Limit(limit).All(&v); err != nil { - return []models.ValueDescriptor{}, errorMap(err) - } - return v, nil -} - -// Get a value descriptor based on the query -func (mc MongoClient) getValueDescriptor(q bson.M) (models.ValueDescriptor, error) { - s := mc.getSessionCopy() - defer s.Close() - - var m models.ValueDescriptor - if err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).Find(q).One(&m); err != nil { - return models.ValueDescriptor{}, errorMap(err) - } - return m, nil -} - -func (mc MongoClient) mapEvents(events []models.Event, errIn error) (ce []contract.Event, err error) { - if errIn != nil { - return []contract.Event{}, errIn - } - - ce = []contract.Event{} - for _, event := range events { - contractEvent, err := event.ToContract(mc) - if err != nil { - return []contract.Event{}, err - } - ce = append(ce, contractEvent) - } - - return -} - -func mapReadings(readings []models.Reading, err error) ([]contract.Reading, error) { - if err != nil { - return []contract.Reading{}, err - } - - mapped := make([]contract.Reading, 0) - for _, r := range readings { - mapped = append(mapped, r.ToContract()) - } - return mapped, nil -} - -func mapValueDescriptors(descriptors []models.ValueDescriptor, err error) ([]contract.ValueDescriptor, error) { - if err != nil { - return []contract.ValueDescriptor{}, err - } - - mapped := make([]contract.ValueDescriptor, 0) - for _, v := range descriptors { - mapped = append(mapped, v.ToContract()) - } - return mapped, nil -} diff --git a/internal/pkg/db/mongo/id.go b/internal/pkg/db/mongo/id.go deleted file mode 100644 index 8ca7ca4ba6..0000000000 --- a/internal/pkg/db/mongo/id.go +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2019 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. - * - *******************************************************************************/ - -package mongo - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - "github.com/globalsign/mgo/bson" - "github.com/google/uuid" -) - -func idToQueryParameters(id string) (name string, value interface{}, err error) { - if !bson.IsObjectIdHex(id) { - _, err := uuid.Parse(id) - if err != nil { // It is some unsupported type of string - return "", "", db.ErrInvalidObjectId - } - name = "uuid" - value = id - } else { - name = "_id" - value = bson.ObjectIdHex(id) - } - return -} - -func idToBsonM(id string) (q bson.M, err error) { - var name string - var value interface{} - name, value, err = idToQueryParameters(id) - if err != nil { - return - } - q = bson.M{name: value} - return -} diff --git a/internal/pkg/db/mongo/metadata.go b/internal/pkg/db/mongo/metadata.go deleted file mode 100644 index bc96b0b31d..0000000000 --- a/internal/pkg/db/mongo/metadata.go +++ /dev/null @@ -1,1087 +0,0 @@ -/******************************************************************************* - * Copyright 2017 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. - *******************************************************************************/ - -package mongo - -import ( - "errors" - "fmt" - - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo" - "github.com/globalsign/mgo/bson" - - types "github.com/edgexfoundry/edgex-go/internal/core/metadata/errors" - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - "github.com/edgexfoundry/edgex-go/internal/pkg/db/mongo/models" -) - -/* ----------------------Device Report --------------------------*/ - -func (mc MongoClient) GetAllDeviceReports() ([]contract.DeviceReport, error) { - return mc.getDeviceReports(bson.M{}) -} - -func (mc MongoClient) GetDeviceReportByName(n string) (contract.DeviceReport, error) { - return mc.getDeviceReport(bson.M{"name": n}) -} - -func (mc MongoClient) GetDeviceReportByDeviceName(n string) ([]contract.DeviceReport, error) { - return mc.getDeviceReports(bson.M{"device": n}) -} - -func (mc MongoClient) GetDeviceReportById(id string) (contract.DeviceReport, error) { - query, err := idToBsonM(id) - if err != nil { - return contract.DeviceReport{}, err - } - return mc.getDeviceReport(query) -} - -func (mc MongoClient) GetDeviceReportsByAction(n string) ([]contract.DeviceReport, error) { - return mc.getDeviceReports(bson.M{"action": n}) -} - -func (mc MongoClient) getDeviceReports(q bson.M) ([]contract.DeviceReport, error) { - s := mc.session.Copy() - defer s.Close() - - var drs []models.DeviceReport - err := s.DB(mc.database.Name).C(db.DeviceReport).Find(q).Sort("queryts").All(&drs) - if err != nil { - return []contract.DeviceReport{}, errorMap(err) - } - - mapped := make([]contract.DeviceReport, 0) - for _, dr := range drs { - mapped = append(mapped, dr.ToContract()) - } - return mapped, nil -} - -func (mc MongoClient) getDeviceReport(q bson.M) (contract.DeviceReport, error) { - s := mc.session.Copy() - defer s.Close() - - var d models.DeviceReport - err := s.DB(mc.database.Name).C(db.DeviceReport).Find(q).One(&d) - if err != nil { - return contract.DeviceReport{}, errorMap(err) - } - return d.ToContract(), nil -} - -func (mc MongoClient) AddDeviceReport(d contract.DeviceReport) (string, error) { - s := mc.session.Copy() - defer s.Close() - - col := s.DB(mc.database.Name).C(db.DeviceReport) - count, err := col.Find(bson.M{"name": d.Name}).Count() - if err != nil { - return "", errorMap(err) - } - if count > 0 { - return "", db.ErrNotUnique - } - - var mapped models.DeviceReport - id, err := mapped.FromContract(d) - if err != nil { - return "", errors.New("FromContract failed") - } - - mapped.TimestampForAdd() - - if err = col.Insert(mapped); err != nil { - return "", errorMap(err) - } - return id, nil -} - -func (mc MongoClient) UpdateDeviceReport(dr contract.DeviceReport) error { - if dr.Id == "" { - byName, err := mc.GetDeviceReportByName(dr.Name) - if err != nil { - return err - } - - dr = byName - } - - var mapped models.DeviceReport - id, err := mapped.FromContract(dr) - if err != nil { - return errors.New("FromContract failed") - } - - mapped.TimestampForUpdate() - - return mc.updateId(db.DeviceReport, id, mapped) -} - -func (mc MongoClient) DeleteDeviceReportById(id string) error { - return mc.deleteById(db.DeviceReport, id) -} - -/* ----------------------------- Device ---------------------------------- */ -func (mc MongoClient) AddDevice(d contract.Device, commands []contract.Command) (string, error) { - s := mc.session.Copy() - defer s.Close() - - col := s.DB(mc.database.Name).C(db.Device) - - // Check if the name exist (Device names must be unique) - count, err := col.Find(bson.M{"name": d.Name}).Count() - if err != nil { - return "", errorMap(err) - } - if count > 0 { - return "", db.ErrNotUnique - } - - var mapped models.Device - id, err := mapped.FromContract(d, mc, mc, mc) - if err != nil { - return "", errors.New("FromContract failed") - } - - mapped.TimestampForAdd() - if err = errorMap(col.Insert(mapped)); err != nil { - return id, err - } - - //add commands based on DeviceProfile.CommandProfile - err = mc.addCommands(commands, mapped.Uuid, mapped.Name) - return id, errorMap(err) -} - -func (mc MongoClient) UpdateDevice(d contract.Device) error { - if d.Id == "" { - byName, err := mc.GetDeviceByName(d.Name) - if err != nil { - return err - } - - d = byName - } - - var mapped models.Device - id, err := mapped.FromContract(d, mc, mc, mc) - if err != nil { - return errors.New("FromContract failed") - } - - mapped.TimestampForUpdate() - - return mc.updateId(db.Device, id, mapped) -} - -func (mc MongoClient) DeleteDeviceById(id string) error { - err := mc.deleteById(db.Device, id) - if err != nil { - return err - } - return mc.deleteCommandByDeviceId(id) -} - -func (mc MongoClient) GetAllDevices() ([]contract.Device, error) { - return mc.getDevices(nil) -} - -func (mc MongoClient) GetDevicesByProfileId(id string) ([]contract.Device, error) { - dp, err := mc.getDeviceProfileById(id) - if err != nil { - return []contract.Device{}, err - } - return mc.getDevices(bson.M{"profile.$id": dp.Id}) -} - -func (mc MongoClient) GetDeviceById(id string) (contract.Device, error) { - query, err := idToBsonM(id) - if err != nil { - return contract.Device{}, err - } - return mc.getDevice(query) -} - -func (mc MongoClient) GetDeviceByName(n string) (contract.Device, error) { - return mc.getDevice(bson.M{"name": n}) -} - -func (mc MongoClient) GetDevicesByServiceId(id string) ([]contract.Device, error) { - ds, err := mc.getDeviceServiceById(id) - if err != nil { - return []contract.Device{}, err - } - return mc.getDevices(bson.M{"service.$id": ds.Id}) -} - -func (mc MongoClient) GetDevicesWithLabel(l string) ([]contract.Device, error) { - return mc.getDevices(bson.M{"labels": bson.M{"$in": []string{l}}}) -} - -func (mc MongoClient) getDevices(q bson.M) ([]contract.Device, error) { - s := mc.session.Copy() - defer s.Close() - - var mds []models.Device - err := s.DB(mc.database.Name).C(db.Device).Find(q).Sort("queryts").All(&mds) - if err != nil { - return []contract.Device{}, errorMap(err) - } - - res := make([]contract.Device, 0) - for _, md := range mds { - d, err := md.ToContract(mc, mc, mc) - if err != nil { - return []contract.Device{}, err - } - res = append(res, d) - } - - return res, nil -} - -func (mc MongoClient) getDevice(q bson.M) (contract.Device, error) { - s := mc.session.Copy() - defer s.Close() - - var d models.Device - if err := s.DB(mc.database.Name).C(db.Device).Find(q).One(&d); err != nil { - return contract.Device{}, errorMap(err) - } - return d.ToContract(mc, mc, mc) -} - -/* -----------------------------Device Profile -----------------------------*/ - -func (mc MongoClient) DBRefToDeviceProfile(dbRef mgo.DBRef) (a models.DeviceProfile, err error) { - s := mc.session.Copy() - defer s.Close() - - if err = s.DB(mc.database.Name).C(db.DeviceProfile).Find(bson.M{"_id": dbRef.Id}).One(&a); err != nil { - return models.DeviceProfile{}, errorMap(err) - } - return -} - -func (mc MongoClient) DeviceProfileToDBRef(model models.DeviceProfile) (dbRef mgo.DBRef, err error) { - // validate model with identity provided in contract actually exists - if model.Id.Valid() { - model, err = mc.getDeviceProfileById(model.Id.Hex()) - } else { - model, err = mc.getDeviceProfileById(model.Uuid) - } - if err != nil { - return - } - - dbRef = mgo.DBRef{Collection: db.DeviceProfile, Id: model.Id} - return -} - -func (mc MongoClient) GetDeviceProfileById(id string) (contract.DeviceProfile, error) { - model, err := mc.getDeviceProfileById(id) - if err != nil { - return contract.DeviceProfile{}, err - } - return model.ToContract() -} - -func (mc MongoClient) getDeviceProfileById(id string) (models.DeviceProfile, error) { - query, err := idToBsonM(id) - if err != nil { - return models.DeviceProfile{}, err - } - return mc.getDeviceProfile(query) -} - -func (mc MongoClient) GetAllDeviceProfiles() ([]contract.DeviceProfile, error) { - return mc.getDeviceProfiles(nil) -} - -func (mc MongoClient) GetDeviceProfilesByModel(model string) ([]contract.DeviceProfile, error) { - return mc.getDeviceProfiles(bson.M{"model": model}) -} - -func (mc MongoClient) GetDeviceProfilesWithLabel(l string) ([]contract.DeviceProfile, error) { - return mc.getDeviceProfiles(bson.M{"labels": bson.M{"$in": []string{l}}}) -} - -func (mc MongoClient) GetDeviceProfilesByManufacturerModel(man string, mod string) ([]contract.DeviceProfile, error) { - return mc.getDeviceProfiles(bson.M{"manufacturer": man, "model": mod}) -} - -func (mc MongoClient) GetDeviceProfilesByManufacturer(man string) ([]contract.DeviceProfile, error) { - return mc.getDeviceProfiles(bson.M{"manufacturer": man}) -} - -func (mc MongoClient) GetDeviceProfileByName(n string) (contract.DeviceProfile, error) { - model, err := mc.getDeviceProfile(bson.M{"name": n}) - if err != nil { - return contract.DeviceProfile{}, err - } - return model.ToContract() -} - -// Get device profiles with the passed query -func (mc MongoClient) getDeviceProfiles(q bson.M) ([]contract.DeviceProfile, error) { - s := mc.session.Copy() - defer s.Close() - - var dps []models.DeviceProfile - err := s.DB(mc.database.Name).C(db.DeviceProfile).Find(q).Sort("queryts").All(&dps) - if err != nil { - return []contract.DeviceProfile{}, errorMap(err) - } - - cdps := make([]contract.DeviceProfile, 0) - for _, dp := range dps { - c, err := dp.ToContract() - if err != nil { - return []contract.DeviceProfile{}, err - } - cdps = append(cdps, c) - } - return cdps, nil -} - -func (mc MongoClient) getDeviceProfile(q bson.M) (d models.DeviceProfile, err error) { - s := mc.session.Copy() - defer s.Close() - - err = s.DB(mc.database.Name).C(db.DeviceProfile).Find(q).One(&d) - if err != nil { - return models.DeviceProfile{}, errorMap(err) - } - - return -} - -func (mc MongoClient) AddDeviceProfile(dp contract.DeviceProfile) (string, error) { - s := mc.session.Copy() - defer s.Close() - if len(dp.Name) == 0 { - return "", db.ErrNameEmpty - } - col := s.DB(mc.database.Name).C(db.DeviceProfile) - count, err := col.Find(bson.M{"name": dp.Name}).Count() - if err != nil { - return "", errorMap(err) - } - if count > 0 { - return "", db.ErrNotUnique - } - - var mapped models.DeviceProfile - id, err := mapped.FromContract(dp) - if err != nil { - return "", err - } - - mapped.TimestampForAdd() - - if err = col.Insert(mapped); err != nil { - return "", errorMap(err) - } - - return id, nil -} - -func (mc MongoClient) UpdateDeviceProfile(dp contract.DeviceProfile) error { - if dp.Id == "" { - byName, err := mc.GetDeviceProfileByName(dp.Name) - if err != nil { - return err - } - - dp = byName - } - - var mapped models.DeviceProfile - id, err := mapped.FromContract(dp) - if err != nil { - return err - } - - mapped.TimestampForUpdate() - - return mc.updateId(db.DeviceProfile, id, mapped) -} - -func (mc MongoClient) DeleteDeviceProfileById(id string) error { - return mc.deleteById(db.DeviceProfile, id) -} - -// -----------------------------------Addressable --------------------------*/ - -func (mc MongoClient) DBRefToAddressable(dbRef mgo.DBRef) (a models.Addressable, err error) { - s := mc.session.Copy() - defer s.Close() - - if err = s.DB(mc.database.Name).C(db.Addressable).Find(bson.M{"_id": dbRef.Id}).One(&a); err != nil { - return models.Addressable{}, errorMap(err) - } - return -} - -func (mc MongoClient) AddressableToDBRef(a models.Addressable) (dbRef mgo.DBRef, err error) { - // validate addressable identity provided in contract actually exists and populate missing Id, Uuid field - var addr models.Addressable - if a.Id.Valid() { - addr, err = mc.getAddressableById(a.Id.Hex()) - } else { - addr, err = mc.getAddressableById(a.Uuid) - } - if err != nil { - return - } - - dbRef = mgo.DBRef{Collection: db.Addressable, Id: addr.Id} - return -} - -func (mc MongoClient) UpdateAddressable(a contract.Addressable) error { - if a.Id == "" { - byName, err := mc.GetAddressableByName(a.Name) - if err != nil { - return err - } - - a = byName - } - - var mapped models.Addressable - id, err := mapped.FromContract(a) - if err != nil { - return err - } - - mapped.TimestampForUpdate() - - return mc.updateId(db.Addressable, id, mapped) -} - -func (mc MongoClient) GetAddressables() ([]contract.Addressable, error) { - return mapAddressables(mc.getAddressablesQuery(bson.M{})) -} - -func (mc MongoClient) getAddressablesQuery(q bson.M) ([]models.Addressable, error) { - s := mc.session.Copy() - defer s.Close() - - items := make([]models.Addressable, 0) - if err := s.DB(mc.database.Name).C(db.Addressable).Find(q).Sort("queryts").All(&items); err != nil { - return []models.Addressable{}, errorMap(err) - } - - return items, nil -} - -func (mc MongoClient) GetAddressableById(id string) (contract.Addressable, error) { - addr, err := mc.getAddressableById(id) - if err != nil { - return contract.Addressable{}, err - } - return addr.ToContract(), nil -} - -func (mc MongoClient) getAddressableById(id string) (models.Addressable, error) { - query, err := idToBsonM(id) - if err != nil { - return models.Addressable{}, err - } - return mc.getAddressable(query) -} - -func (mc MongoClient) AddAddressable(a contract.Addressable) (string, error) { - s := mc.session.Copy() - defer s.Close() - - var mapped models.Addressable - id, err := mapped.FromContract(a) - if err != nil { - return "", err - } - - col := s.DB(mc.database.Name).C(db.Addressable) - - // check if the name exist - count, err := col.Find(bson.M{"name": mapped.Name}).Count() - if err != nil { - return a.Id, errorMap(err) - } - if count > 0 { - return a.Id, db.ErrNotUnique - } - - mapped.TimestampForAdd() - - if err = col.Insert(mapped); err != nil { - return "", errorMap(err) - } - return id, nil -} - -func (mc MongoClient) GetAddressableByName(n string) (contract.Addressable, error) { - addr, err := mc.getAddressableByName(n) - if err != nil { - return contract.Addressable{}, err - } - return addr.ToContract(), nil -} - -func (mc MongoClient) getAddressableByName(n string) (models.Addressable, error) { - addr, err := mc.getAddressable(bson.M{"name": n}) - if err != nil { - return models.Addressable{}, err - } - return addr, nil -} - -func (mc MongoClient) GetAddressablesByTopic(t string) ([]contract.Addressable, error) { - return mapAddressables(mc.getAddressablesQuery(bson.M{"topic": t})) -} - -func (mc MongoClient) GetAddressablesByPort(p int) ([]contract.Addressable, error) { - return mapAddressables(mc.getAddressablesQuery(bson.M{"port": p})) -} - -func (mc MongoClient) GetAddressablesByPublisher(p string) ([]contract.Addressable, error) { - return mapAddressables(mc.getAddressablesQuery(bson.M{"publisher": p})) -} - -func (mc MongoClient) GetAddressablesByAddress(add string) ([]contract.Addressable, error) { - return mapAddressables(mc.getAddressablesQuery(bson.M{"address": add})) -} - -func (mc MongoClient) getAddressable(q bson.M) (models.Addressable, error) { - s := mc.session.Copy() - defer s.Close() - - var a models.Addressable - err := s.DB(mc.database.Name).C(db.Addressable).Find(q).One(&a) - if err != nil { - return models.Addressable{}, errorMap(err) - } - return a, nil -} - -func (mc MongoClient) DeleteAddressableById(id string) error { - return mc.deleteById(db.Addressable, id) -} - -func mapAddressables(as []models.Addressable, err error) ([]contract.Addressable, error) { - mapped := make([]contract.Addressable, 0) - if err != nil { - return mapped, errorMap(err) - } - for _, a := range as { - mapped = append(mapped, a.ToContract()) - } - return mapped, nil -} - -/* ----------------------------- Device Service ----------------------------------*/ - -func (mc MongoClient) DBRefToDeviceService(dbRef mgo.DBRef) (ds models.DeviceService, err error) { - s := mc.session.Copy() - defer s.Close() - - if err = s.DB(mc.database.Name).C(db.DeviceService).Find(bson.M{"_id": dbRef.Id}).One(&ds); err != nil { - return models.DeviceService{}, errorMap(err) - } - return -} - -func (mc MongoClient) DeviceServiceToDBRef(model models.DeviceService) (dbRef mgo.DBRef, err error) { - // validate model with identity provided in contract actually exists - if model.Id.Valid() { - model, err = mc.getDeviceServiceById(model.Id.Hex()) - } else { - model, err = mc.getDeviceServiceById(model.Uuid) - } - if err != nil { - return - } - - dbRef = mgo.DBRef{Collection: db.DeviceService, Id: model.Id} - return -} - -func (mc MongoClient) GetDeviceServiceByName(n string) (contract.DeviceService, error) { - ds, err := mc.deviceService(bson.M{"name": n}) - if err != nil { - return contract.DeviceService{}, err - } - return ds.ToContract(mc) -} - -func (mc MongoClient) GetDeviceServiceById(id string) (contract.DeviceService, error) { - ds, err := mc.getDeviceServiceById(id) - if err != nil { - return contract.DeviceService{}, err - } - return ds.ToContract(mc) -} - -func (mc MongoClient) getDeviceServiceById(id string) (models.DeviceService, error) { - query, err := idToBsonM(id) - if err != nil { - return models.DeviceService{}, err - } - return mc.deviceService(query) -} - -func (mc MongoClient) GetAllDeviceServices() ([]contract.DeviceService, error) { - return mc.getDeviceServices(bson.M{}) -} - -func (mc MongoClient) GetDeviceServicesByAddressableId(id string) ([]contract.DeviceService, error) { - addr, err := mc.getAddressableById(id) - if err != nil { - return []contract.DeviceService{}, err - } - return mc.getDeviceServices(bson.M{"addressable.$id": addr.Id}) -} - -func (mc MongoClient) GetDeviceServicesWithLabel(l string) ([]contract.DeviceService, error) { - return mc.getDeviceServices(bson.M{"labels": bson.M{"$in": []string{l}}}) -} - -func (mc MongoClient) getDeviceServices(q bson.M) (dss []contract.DeviceService, err error) { - dss = []contract.DeviceService{} - mds, err := mc.deviceServices(q) - if err != nil { - return - } - for _, ds := range mds { - cds, err := ds.ToContract(mc) - if err != nil { - return []contract.DeviceService{}, err - } - dss = append(dss, cds) - } - - return dss, nil -} - -func (mc MongoClient) deviceServices(q bson.M) (dss []models.DeviceService, err error) { - s := mc.session.Copy() - defer s.Close() - if err = s.DB(mc.database.Name).C(db.DeviceService).Find(q).Sort("queryts").All(&dss); err != nil { - return []models.DeviceService{}, errorMap(err) - } - - return -} - -func (mc MongoClient) getDeviceService(q bson.M) (ds contract.DeviceService, err error) { - mds, err := mc.deviceService(q) - if err != nil { - return contract.DeviceService{}, err - } - ds, err = mds.ToContract(mc) - return -} - -func (mc MongoClient) deviceService(q bson.M) (models.DeviceService, error) { - s := mc.session.Copy() - defer s.Close() - - var ds models.DeviceService - err := s.DB(mc.database.Name).C(db.DeviceService).Find(q).One(&ds) - if err != nil { - return models.DeviceService{}, errorMap(err) - } - - return ds, nil -} - -func (mc MongoClient) AddDeviceService(ds contract.DeviceService) (string, error) { - s := mc.session.Copy() - defer s.Close() - - var mapped models.DeviceService - id, err := mapped.FromContract(ds, mc) - if err != nil { - return "", errors.New("FromContract failed") - } - - mapped.TimestampForAdd() - - if err = s.DB(mc.database.Name).C(db.DeviceService).Insert(mapped); err != nil { - return "", errorMap(err) - } - return id, nil -} - -func (mc MongoClient) UpdateDeviceService(ds contract.DeviceService) error { - if ds.Id == "" { - byName, err := mc.GetDeviceServiceByName(ds.Name) - if err != nil { - return err - } - - ds = byName - } - - var mapped models.DeviceService - id, err := mapped.FromContract(ds, mc) - if err != nil { - return errors.New("FromContract failed") - } - - mapped.TimestampForUpdate() - - return mc.updateId(db.DeviceService, id, mapped) -} - -func (mc MongoClient) DeleteDeviceServiceById(id string) error { - return mc.deleteById(db.DeviceService, id) -} - -func (mc MongoClient) validateDeviceExist(id string) (err error) { - s := mc.session.Copy() - defer s.Close() - - dQuery, err := idToBsonM(id) - if err != nil { - return - } - count, err := s.DB(mc.database.Name).C(db.Device).Find(dQuery).Select(bson.M{"_id": 1}).Limit(1).Count() - if err != nil { - return - } - if count != 1 { - return types.NewErrItemNotFound(fmt.Sprintf("device with id %s not found", id)) - } - - return nil -} - -// ----------------------Provision Watcher -----------------------------*/ -func (mc MongoClient) GetAllProvisionWatchers() (pw []contract.ProvisionWatcher, err error) { - return mc.getProvisionWatchers(bson.M{}) -} - -func (mc MongoClient) GetProvisionWatcherByName(n string) (pw contract.ProvisionWatcher, err error) { - return mc.GetProvisionWatcher(bson.M{"name": n}) -} - -func (mc MongoClient) GetProvisionWatchersByIdentifier(k string, v string) (pw []contract.ProvisionWatcher, err error) { - return mc.getProvisionWatchers(bson.M{"identifiers." + k: v}) -} - -func (mc MongoClient) GetProvisionWatchersByServiceId(id string) (pw []contract.ProvisionWatcher, err error) { - ds, err := mc.getDeviceServiceById(id) - if err != nil { - return []contract.ProvisionWatcher{}, err - } - return mc.getProvisionWatchers(bson.M{"service.$id": ds.Id}) -} - -func (mc MongoClient) GetProvisionWatchersByProfileId(id string) (pw []contract.ProvisionWatcher, err error) { - dp, err := mc.getDeviceProfileById(id) - if err != nil { - return []contract.ProvisionWatcher{}, err - } - return mc.getProvisionWatchers(bson.M{"profile.$id": dp.Id}) -} - -func (mc MongoClient) GetProvisionWatcherById(id string) (pw contract.ProvisionWatcher, err error) { - query, err := idToBsonM(id) - if err != nil { - return contract.ProvisionWatcher{}, err - } - - pw, err = mc.GetProvisionWatcher(query) - if err != nil { - return contract.ProvisionWatcher{}, err - } - - return -} - -func (mc MongoClient) GetProvisionWatcher(q bson.M) (pw contract.ProvisionWatcher, err error) { - mpw, err := mc.getProvisionWatcher(q) - if err != nil { - return - } - - pw, err = mpw.ToContract(mc, mc, mc) - - return -} - -func (mc MongoClient) getProvisionWatcher(q bson.M) (mpw models.ProvisionWatcher, err error) { - s := mc.session.Copy() - defer s.Close() - - if err = s.DB(mc.database.Name).C(db.ProvisionWatcher).Find(q).One(&mpw); err != nil { - return models.ProvisionWatcher{}, errorMap(err) - } - - return mpw, nil -} - -func (mc MongoClient) getProvisionWatchers(q bson.M) (pws []contract.ProvisionWatcher, err error) { - mpws, err := mc.provisionWatchers(q) - - cpws := make([]contract.ProvisionWatcher, 0) - for _, mpw := range mpws { - cpw, err := mpw.ToContract(mc, mc, mc) - if err != nil { - return []contract.ProvisionWatcher{}, err - } - cpws = append(cpws, cpw) - } - - return cpws, nil -} - -func (mc MongoClient) provisionWatchers(q bson.M) (pws []models.ProvisionWatcher, err error) { - s := mc.session.Copy() - defer s.Close() - - var mpws []models.ProvisionWatcher - if err = s.DB(mc.database.Name).C(db.ProvisionWatcher).Find(q).Sort("queryts").All(&mpws); err != nil { - return []models.ProvisionWatcher{}, errorMap(err) - } - - return mpws, nil -} - -func (mc MongoClient) AddProvisionWatcher(pw contract.ProvisionWatcher) (string, error) { - s := mc.session.Copy() - defer s.Close() - col := s.DB(mc.database.Name).C(db.ProvisionWatcher) - count, err := col.Find(bson.M{"name": pw.Name}).Count() - if err != nil { - return "", errorMap(err) - } - if count > 0 { - return "", db.ErrNotUnique - } - - // get Device Service - var dev contract.DeviceService - switch { - case pw.Service.Id != "": - dev, err = mc.GetDeviceServiceById(pw.Service.Id) - case pw.Service.Name != "": - dev, err = mc.GetDeviceServiceByName(pw.Service.Name) - default: - return "", errors.New("Device Service ID or Name is required") - } - if err != nil { - return "", err - } - pw.Service = dev - - // get Device Profile - var dp contract.DeviceProfile - switch { - case pw.Profile.Id != "": - dp, err = mc.GetDeviceProfileById(pw.Profile.Id) - case pw.Profile.Name != "": - dp, err = mc.GetDeviceProfileByName(pw.Profile.Name) - default: - return "", errors.New("Device Profile ID or Name is required") - } - if err != nil { - return "", err - } - pw.Profile = dp - - var mapped models.ProvisionWatcher - id, err := mapped.FromContract(pw, mc, mc, mc) - if err != nil { - return "", errors.New("ProvisionWatcher FromContract() failed") - } - - mapped.TimestampForAdd() - - err = col.Insert(mapped) - if err != nil { - return "", errorMap(err) - } - return id, nil -} - -func (mc MongoClient) UpdateProvisionWatcher(pw contract.ProvisionWatcher) error { - if pw.Id == "" { - byName, err := mc.GetProvisionWatcherByName(pw.Name) - if err != nil { - return err - } - - pw = byName - } - - if pw.Profile.Id == "" { - byName, err := mc.GetDeviceProfileByName(pw.Profile.Name) - if err != nil { - return err - } - - pw.Profile = byName - } - - if pw.Service.Id == "" { - byName, err := mc.GetDeviceServiceByName(pw.Service.Name) - if err != nil { - return err - } - - pw.Service = byName - } - - var mapped models.ProvisionWatcher - id, err := mapped.FromContract(pw, mc, mc, mc) - if err != nil { - return err - } - - mapped.TimestampForUpdate() - - return mc.updateId(db.ProvisionWatcher, id, mapped) -} - -func (mc MongoClient) DeleteProvisionWatcherById(id string) error { - return mc.deleteById(db.ProvisionWatcher, id) -} - -// ------------------------Command -------------------------------------*/ - -func (mc MongoClient) GetAllCommands() ([]contract.Command, error) { - return mc.getCommands(bson.M{}) -} - -func (mc MongoClient) GetCommandById(id string) (contract.Command, error) { - query, err := idToBsonM(id) - if err != nil { - return contract.Command{}, err - } - return mc.getCommand(query) -} - -func (mc MongoClient) GetCommandsByName(n string) ([]contract.Command, error) { - return mc.getCommands(bson.M{"name": n}) -} - -func (mc MongoClient) GetCommandsByDeviceId(did string) ([]contract.Command, error) { - if err := mc.validateDeviceExist(did); err != nil { - return nil, err - } - return mc.getCommands(bson.M{"deviceId": did}) -} - -func (mc MongoClient) GetCommandByNameAndDeviceId(cname string, did string) (contract.Command, error) { - return mc.getCommand(bson.M{"deviceId": did, "name": cname}) -} - -func (mc MongoClient) deleteCommandByDeviceId(did string) error { - s := mc.session.Copy() - defer s.Close() - _, err := s.DB(mc.database.Name).C(db.Command).RemoveAll(bson.D{{Name: "deviceId", Value: did}}) - return errorMap(err) -} - -func (mc MongoClient) addCommands(commands []contract.Command, did string, dname string) (err error) { - s := mc.session.Copy() - defer s.Close() - for _, c := range commands { - var cMapped models.Command - if _, err = cMapped.FromContract(c, did, dname); err != nil { - return errors.New("FromContract failed") - } - cMapped.TimestampForAdd() - if err = s.DB(mc.database.Name).C(db.Command).Insert(cMapped); err != nil { - return err - } - } - return err -} - -func (mc MongoClient) getCommand(q bson.M) (contract.Command, error) { - s := mc.session.Copy() - defer s.Close() - - var cmd models.Command - if err := s.DB(mc.database.Name).C(db.Command).Find(q).One(&cmd); err != nil { - return contract.Command{}, errorMap(err) - } - return cmd.ToContract(), nil -} - -func (mc MongoClient) getCommands(q bson.M) ([]contract.Command, error) { - s := mc.session.Copy() - defer s.Close() - - var cmds []models.Command - err := s.DB(mc.database.Name).C(db.Command).Find(q).Sort("queryts").All(&cmds) - - return mapCommands(cmds, err) -} - -func mapCommands(commands []models.Command, err error) ([]contract.Command, error) { - if err != nil { - return nil, errorMap(err) - } - - mapped := make([]contract.Command, 0) - for _, cmd := range commands { - mapped = append(mapped, cmd.ToContract()) - } - - return mapped, nil -} - -// Scrub all metadata -func (mc MongoClient) ScrubMetadata() error { - s := mc.session.Copy() - defer s.Close() - - _, err := s.DB(mc.database.Name).C(db.Addressable).RemoveAll(nil) - if err != nil { - return errorMap(err) - } - _, err = s.DB(mc.database.Name).C(db.DeviceService).RemoveAll(nil) - if err != nil { - return errorMap(err) - } - _, err = s.DB(mc.database.Name).C(db.DeviceProfile).RemoveAll(nil) - if err != nil { - return errorMap(err) - } - _, err = s.DB(mc.database.Name).C(db.DeviceReport).RemoveAll(nil) - if err != nil { - return errorMap(err) - } - _, err = s.DB(mc.database.Name).C(db.Command).RemoveAll(nil) - if err != nil { - return errorMap(err) - } - _, err = s.DB(mc.database.Name).C(db.Device).RemoveAll(nil) - if err != nil { - return errorMap(err) - } - _, err = s.DB(mc.database.Name).C(db.ProvisionWatcher).RemoveAll(nil) - if err != nil { - return errorMap(err) - } - - return nil -} diff --git a/internal/pkg/db/mongo/models/addressable.go b/internal/pkg/db/mongo/models/addressable.go deleted file mode 100644 index ef87f11b45..0000000000 --- a/internal/pkg/db/mongo/models/addressable.go +++ /dev/null @@ -1,110 +0,0 @@ -/******************************************************************************* - * Copyright 2018 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. - *******************************************************************************/ - -// Package models provides an internal representation of data structures that can be used when interacting with MongoDB. -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release and no new functionality should be added; -// Only bugs which address legacy issues -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo" - "github.com/globalsign/mgo/bson" -) - -type addressableTransform interface { - DBRefToAddressable(dbRef mgo.DBRef) (model Addressable, err error) - AddressableToDBRef(model Addressable) (dbRef mgo.DBRef, err error) - GetAddressableByName(n string) (contract.Addressable, error) -} - -// Addressable -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Addressable struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Name string `bson:"name"` - Protocol string `bson:"protocol"` // Protocol for the address (HTTP/TCP) - HTTPMethod string `bson:"method"` // Method for connecting (i.e. POST) - Address string `bson:"address"` // Address of the addressable - Port int `bson:"port"` // Port for the address - Path string `bson:"path"` // Path for callbacks - Publisher string `bson:"publisher"` // For message bus protocols - User string `bson:"user"` // User id for authentication - Password string `bson:"password"` // Password of the user for authentication for the addressable - Topic string `bson:"topic"` // Topic for message bus addressables -} - -func (a *Addressable) ToContract() (c contract.Addressable) { - // Always hand back the UUID as the contract event ID unless it's blank (an old event, for example blackbox test scripts - id := a.Uuid - if id == "" { - id = a.Id.Hex() - } - - c.Created = a.Created - c.Modified = a.Modified - c.Origin = a.Origin - c.Id = id - c.Name = a.Name - c.Protocol = a.Protocol - c.HTTPMethod = a.HTTPMethod - c.Address = a.Address - c.Port = a.Port - c.Path = a.Path - c.Publisher = a.Publisher - c.User = a.User - c.Password = a.Password - c.Topic = a.Topic - - return -} - -func (a *Addressable) FromContract(from contract.Addressable) (id string, err error) { - if a.Id, a.Uuid, err = fromContractId(from.Id); err != nil { - return - } - - a.Created = from.Created - a.Modified = from.Modified - a.Origin = from.Origin - a.Name = from.Name - a.Protocol = from.Protocol - a.HTTPMethod = from.HTTPMethod - a.Address = from.Address - a.Port = from.Port - a.Path = from.Path - a.Publisher = from.Publisher - a.User = from.User - a.Password = from.Password - a.Topic = from.Topic - - id = toContractId(a.Id, a.Uuid) - return -} - -func (a *Addressable) TimestampForUpdate() { - a.Modified = db.MakeTimestamp() -} - -func (a *Addressable) TimestampForAdd() { - a.TimestampForUpdate() - a.Created = a.Modified -} diff --git a/internal/pkg/db/mongo/models/channel.go b/internal/pkg/db/mongo/models/channel.go deleted file mode 100644 index 0e05401fed..0000000000 --- a/internal/pkg/db/mongo/models/channel.go +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies 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. - * - *******************************************************************************/ -package models - -import contract "github.com/edgexfoundry/go-mod-core-contracts/models" - -// Channel -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Channel struct { - Type contract.ChannelType `bson:"type,omitempty"` - MailAddresses []string `bson:"mailAddresses,omitempty"` - Url string `bson:"url,omitempty"` -} - -func (channel *Channel) ToContract() (c contract.Channel) { - c.Type = channel.Type - c.MailAddresses = channel.MailAddresses - c.Url = channel.Url - return -} - -func (channel *Channel) FromContract(from contract.Channel) { - channel.Type = from.Type - channel.MailAddresses = from.MailAddresses - channel.Url = from.Url -} diff --git a/internal/pkg/db/mongo/models/command.go b/internal/pkg/db/mongo/models/command.go deleted file mode 100644 index d41b0864e9..0000000000 --- a/internal/pkg/db/mongo/models/command.go +++ /dev/null @@ -1,171 +0,0 @@ -/******************************************************************************* - * Copyright 2018 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. - *******************************************************************************/ - -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" -) - -// Response -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Response struct { - Code string `bson:"code"` - Description string `bson:"description"` - ExpectedValues []string `bson:"expectedValues"` -} - -// Get -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Get struct { - Path string `bson:"path"` // path used by service for action on a device or sensor - Responses []Response `bson:"responses"` // responses from get or put requests to service - URL string // url for requests from command service -} - -// Put -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Put struct { - Path string `bson:"path"` // path used by service for action on a device or sensor - Responses []Response `bson:"responses"` // responses from get or put requests to service - URL string // url for requests from command service - ParameterNames []string `bson:"parameterNames"` -} - -// CommandProfile -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type CommandProfile struct { - Name string `bson:"name"` - Get Get `bson:"get"` - Put Put `bson:"put"` -} - -func (c *CommandProfile) ToContract() (cmd contract.Command) { - cmd.Get = contract.Get{} - cmd.Get.Path = c.Get.Path - cmd.Get.URL = c.Get.URL - cmd.Get.Responses = []contract.Response{} - for _, r := range c.Get.Responses { - cmd.Get.Responses = append(cmd.Get.Responses, contract.Response{ - Code: r.Code, - Description: r.Description, - ExpectedValues: r.ExpectedValues, - }) - } - - cmd.Put = contract.Put{} - cmd.Put.Path = c.Put.Path - cmd.Put.Responses = []contract.Response{} - for _, r := range c.Put.Responses { - cmd.Put.Responses = append(cmd.Put.Responses, contract.Response{ - Code: r.Code, - Description: r.Description, - ExpectedValues: r.ExpectedValues, - }) - } - cmd.Put.URL = c.Put.URL - cmd.Put.ParameterNames = c.Put.ParameterNames - - cmd.Name = c.Name - - return -} - -func (c *CommandProfile) FromContract(from contract.Command) (contractId string, err error) { - c.Name = from.Name - - c.Get = Get{} - c.Get.Path = from.Get.Path - c.Get.URL = from.Get.URL - c.Get.Responses = []Response{} - for _, val := range from.Get.Responses { - c.Get.Responses = append(c.Get.Responses, Response{ - Code: val.Code, - Description: val.Description, - ExpectedValues: val.ExpectedValues, - }) - } - - c.Put = Put{} - c.Put.Path = from.Put.Path - c.Put.Responses = []Response{} - for _, val := range from.Put.Responses { - c.Put.Responses = append(c.Put.Responses, Response{ - Code: val.Code, - Description: val.Description, - ExpectedValues: val.ExpectedValues, - }) - } - c.Put.URL = from.Put.URL - c.Put.ParameterNames = from.Put.ParameterNames - return -} - -func (c *Command) TimestampForUpdate() { - c.Modified = db.MakeTimestamp() -} - -func (c *Command) TimestampForAdd() { - c.TimestampForUpdate() - c.Created = c.Modified -} - -// Command -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Command struct { - CommandProfile `bson:",inline"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - DeviceID string `bson:"deviceId"` - DeviceName string `bson:"deviceName"` - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` -} - -func (c *Command) ToContract() (cmd contract.Command) { - cmd = c.CommandProfile.ToContract() - id := c.Uuid - if id == "" { - id = c.Id.Hex() - } - cmd.Id = id - cmd.Created = c.Created - cmd.Modified = c.Modified - cmd.Origin = c.Origin - return -} - -func (c *Command) FromContract(fromCommand contract.Command, fromDeviceId string, fromDeviceName string) (contractId string, err error) { - c.Id, c.Uuid, err = fromContractId(fromCommand.Id) - if err != nil { - return - } - c.CommandProfile.FromContract(fromCommand) - c.DeviceID = fromDeviceId - c.DeviceName = fromDeviceName - c.Created = fromCommand.Created - c.Modified = fromCommand.Modified - c.Origin = fromCommand.Origin - - contractId = toContractId(c.Id, c.Uuid) - return -} diff --git a/internal/pkg/db/mongo/models/device.go b/internal/pkg/db/mongo/models/device.go deleted file mode 100644 index a72e78fdc6..0000000000 --- a/internal/pkg/db/mongo/models/device.go +++ /dev/null @@ -1,164 +0,0 @@ -/******************************************************************************* - * Copyright 2019 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. - *******************************************************************************/ - -package models - -import ( - "encoding/json" - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo" - "github.com/globalsign/mgo/bson" -) - -// Device -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Device struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Description string `bson:"description"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Protocols string `bson:"protocols,omitempty"` //Contains a JSON representation of the supported protocols for the device - AutoEvents string `bson:"autoEvents,omitempty"` //Contains a JSON representation of the device's auto-generated events - Name string `bson:"name"` // Unique name for identifying a device - AdminState contract.AdminState `bson:"adminState"` // Admin state (locked/unlocked) - OperatingState contract.OperatingState `bson:"operatingState"` // Operating state (enabled/disabled) - LastConnected int64 `bson:"lastConnected"` // Time (milliseconds) that the device last provided any feedback or responded to any request - LastReported int64 `bson:"lastReported"` // Time (milliseconds) that the device reported data to the core microservice - Labels []string `bson:"labels"` // Other labels applied to the device to help with searching - Location interface{} `bson:"location"` // Device service specific location (interface{} is an empty interface so it can be anything) - Service mgo.DBRef `bson:"service"` // Associated Device Service - One per device - Profile mgo.DBRef `bson:"profile"` // Associated Device Profile - Describes the device - ProfileName string `bson:"profileName"` // Associated Device Profile Name -} - -func (d *Device) ToContract(dsTransform deviceServiceTransform, dpTransform deviceProfileTransform, aTransform addressableTransform) (contract.Device, error) { - // Always hand back the UUID as the contract command ID unless it's blank (an old command, for example blackbox test scripts) - id := d.Uuid - if id == "" { - id = d.Id.Hex() - } - - var err error - var result contract.Device - - result.Created = d.Created - result.Modified = d.Modified - result.Origin = d.Origin - result.Description = d.Description - result.Id = id - result.Name = d.Name - result.AdminState = d.AdminState - result.OperatingState = d.OperatingState - - p := make(map[string]contract.ProtocolProperties) - err = json.Unmarshal([]byte(d.Protocols), &p) - if err != nil { - return contract.Device{}, err - } - result.Protocols = p - - ae := make([]contract.AutoEvent, 0) - err = json.Unmarshal([]byte(d.AutoEvents), &ae) - if err != nil { - return contract.Device{}, err - } - result.AutoEvents = ae - result.LastConnected = d.LastConnected - result.LastReported = d.LastReported - result.Labels = d.Labels - result.Location = d.Location - - dsModel, err := dsTransform.DBRefToDeviceService(d.Service) - if err != nil { - return contract.Device{}, err - } - result.Service, err = dsModel.ToContract(aTransform) - if err != nil { - return contract.Device{}, err - } - - dpModel, err := dpTransform.DBRefToDeviceProfile(d.Profile) - if err != nil { - return contract.Device{}, err - } - result.Profile, err = dpModel.ToContract() - if err != nil { - return contract.Device{}, err - } - - return result, nil -} - -func (d *Device) FromContract(from contract.Device, dsTransform deviceServiceTransform, dpTransform deviceProfileTransform, aTransform addressableTransform) (string, error) { - var err error - if d.Id, d.Uuid, err = fromContractId(from.Id); err != nil { - return "", err - } - - d.Created = from.Created - d.Modified = from.Modified - d.Origin = from.Origin - d.Description = from.Description - d.Name = from.Name - d.AdminState = from.AdminState - d.OperatingState = from.OperatingState - - p, err := json.Marshal(from.Protocols) - if err != nil { - return "", err - } - d.Protocols = string(p) - - ae, err := json.Marshal(from.AutoEvents) - if err != nil { - return "", err - } - d.AutoEvents = string(ae) - d.LastConnected = from.LastConnected - d.LastReported = from.LastReported - d.Labels = from.Labels - d.Location = from.Location - - var dsModel DeviceService - if _, err = dsModel.FromContract(from.Service, aTransform); err != nil { - return "", err - } - if d.Service, err = dsTransform.DeviceServiceToDBRef(dsModel); err != nil { - return "", err - } - - var dpModel DeviceProfile - if _, err = dpModel.FromContract(from.Profile); err != nil { - return "", err - } - d.ProfileName = dpModel.Name - if d.Profile, err = dpTransform.DeviceProfileToDBRef(dpModel); err != nil { - return "", err - } - - return toContractId(d.Id, d.Uuid), nil -} - -func (d *Device) TimestampForUpdate() { - d.Modified = db.MakeTimestamp() -} - -func (d *Device) TimestampForAdd() { - d.TimestampForUpdate() - d.Created = d.Modified -} diff --git a/internal/pkg/db/mongo/models/deviceprofile.go b/internal/pkg/db/mongo/models/deviceprofile.go deleted file mode 100644 index 8aa5dffe76..0000000000 --- a/internal/pkg/db/mongo/models/deviceprofile.go +++ /dev/null @@ -1,309 +0,0 @@ -/******************************************************************************* - * Copyright 2019 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. - *******************************************************************************/ - -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo" - "github.com/globalsign/mgo/bson" -) - -type deviceProfileTransform interface { - DBRefToDeviceProfile(dbRef mgo.DBRef) (model DeviceProfile, err error) - DeviceProfileToDBRef(model DeviceProfile) (dbRef mgo.DBRef, err error) -} - -// PropertyValue -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type PropertyValue struct { - Type string `bson:"type"` // ValueDescriptor Type of property after transformations - ReadWrite string `bson:"readWrite"` // Read/Write Permissions set for this property - Minimum string `bson:"minimum"` // Minimum value that can be get/set from this property - Maximum string `bson:"maximum"` // Maximum value that can be get/set from this property - DefaultValue string `bson:"defaultValue"` // Default value set to this property if no argument is passed - Size string `bson:"size"` // Size of this property in its type (i.e. bytes for numeric types, characters for string types) - Mask string `bson:"mask"` // Mask to be applied prior to get/set of property - Shift string `bson:"shift"` // Shift to be applied after masking, prior to get/set of property - Scale string `bson:"scale"` // Multiplicative factor to be applied after shifting, prior to get/set of property - Offset string `bson:"offset"` // Additive factor to be applied after multiplying, prior to get/set of property - Base string `bson:"base"` // Base for property to be applied to, leave 0 for no power operation (i.e. base ^ property: 2 ^ 10) - Assertion string `bson:"assertion"` // Required value of the property, set for checking error state. Failing an assertion condition will mark the device with an error state - Precision string `bson:"precision"` - FloatEncoding string `bson:"floatEncoding"` // FloatEncoding indicates the representation of floating value of reading. It should be 'Base64' or 'eNotation' - MediaType string `bson:"mediaType"` -} - -// Units -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Units struct { - Type string `bson:"type"` - ReadWrite string `bson:"readWrite"` - DefaultValue string `bson:"defaultValue"` -} - -// ProfileProperty -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type ProfileProperty struct { - Value PropertyValue `bson:"value"` - Units Units `bson:"units"` -} - -// DeviceResource -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type DeviceResource struct { - Description string `bson:"description"` - Name string `bson:"name"` - Tag string `bson:"tag"` - Properties ProfileProperty `bson:"properties"` - Attributes map[string]string `bson:"attributes"` -} - -// ResourceOperation -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type ResourceOperation struct { - Index string `bson:"index"` - Operation string `bson:"operation"` - Object string `bson:"object"` - DeviceResource string `bson:"deviceresource"` - Parameter string `bson:"parameter"` - Resource string `bson:"resource"` - DeviceCommand string `bson:"devicecommand"` - Secondary []string `bson:"secondary"` - Mappings map[string]string `bson:"mappings"` -} - -// ProfileResource -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type ProfileResource struct { - Name string `bson:"name"` - Get []ResourceOperation `bson:"get"` - Set []ResourceOperation `bson:"set"` -} - -// Addressable -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type DeviceProfile struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Description string `bson:"description"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Name string `bson:"name"` - Manufacturer string `bson:"manufacturer"` - Model string `bson:"model"` - Labels []string `bson:"labels"` - DeviceResources []DeviceResource `bson:"deviceResources"` - DeviceCommands []ProfileResource `bson:"resources"` - CoreCommands []CommandProfile `bson:"commands"` -} - -func (dp *DeviceProfile) ToContract() (c contract.DeviceProfile, err error) { - id := dp.Uuid - if id == "" { - id = dp.Id.Hex() - } - - c.Id = id - c.Name = dp.Name - c.Manufacturer = dp.Manufacturer - c.Model = dp.Model - c.Labels = dp.Labels - c.Created = dp.Created - c.Modified = dp.Modified - c.Origin = dp.Origin - c.Description = dp.Description - - for _, dr := range dp.DeviceResources { - var cdo contract.DeviceResource - - cdo.Description = dr.Description - cdo.Name = dr.Name - cdo.Tag = dr.Tag - - cdo.Properties.Value.Type = dr.Properties.Value.Type - cdo.Properties.Value.ReadWrite = dr.Properties.Value.ReadWrite - cdo.Properties.Value.Minimum = dr.Properties.Value.Minimum - cdo.Properties.Value.Maximum = dr.Properties.Value.Maximum - cdo.Properties.Value.DefaultValue = dr.Properties.Value.DefaultValue - cdo.Properties.Value.Size = dr.Properties.Value.Size - cdo.Properties.Value.Mask = dr.Properties.Value.Mask - cdo.Properties.Value.Shift = dr.Properties.Value.Shift - cdo.Properties.Value.Scale = dr.Properties.Value.Scale - cdo.Properties.Value.Offset = dr.Properties.Value.Offset - cdo.Properties.Value.Base = dr.Properties.Value.Base - cdo.Properties.Value.Assertion = dr.Properties.Value.Assertion - cdo.Properties.Value.Precision = dr.Properties.Value.Precision - cdo.Properties.Value.FloatEncoding = dr.Properties.Value.FloatEncoding - cdo.Properties.Value.MediaType = dr.Properties.Value.MediaType - - cdo.Properties.Units.Type = dr.Properties.Units.Type - cdo.Properties.Units.ReadWrite = dr.Properties.Units.ReadWrite - cdo.Properties.Units.DefaultValue = dr.Properties.Units.DefaultValue - - cdo.Attributes = dr.Attributes - - c.DeviceResources = append(c.DeviceResources, cdo) - } - - for _, r := range dp.DeviceCommands { - var cpr contract.ProfileResource - cpr.Name = r.Name - for _, ro := range r.Get { - cpr.Get = append(cpr.Get, contract.ResourceOperation{ - Index: ro.Index, - Operation: ro.Operation, - Object: ro.Object, - DeviceResource: ro.DeviceResource, - Parameter: ro.Parameter, - Resource: ro.Resource, - DeviceCommand: ro.DeviceCommand, - Secondary: ro.Secondary, - Mappings: ro.Mappings, - }) - } - - for _, ro := range r.Set { - cpr.Set = append(cpr.Set, contract.ResourceOperation{ - Index: ro.Index, - Operation: ro.Operation, - Object: ro.Object, - DeviceResource: ro.DeviceResource, - Parameter: ro.Parameter, - Resource: ro.Resource, - DeviceCommand: ro.DeviceCommand, - Secondary: ro.Secondary, - Mappings: ro.Mappings, - }) - } - - c.DeviceCommands = append(c.DeviceCommands, cpr) - } - - for _, from := range dp.CoreCommands { - c.CoreCommands = append(c.CoreCommands, from.ToContract()) - } - return -} - -func (dp *DeviceProfile) FromContract(from contract.DeviceProfile) (contractId string, err error) { - dp.Id, dp.Uuid, err = fromContractId(from.Id) - if err != nil { - return - } - - dp.Name = from.Name - dp.Manufacturer = from.Manufacturer - dp.Model = from.Model - dp.Labels = from.Labels - - dp.Created = from.Created - dp.Modified = from.Modified - dp.Origin = from.Origin - dp.Description = from.Description - - for _, dr := range from.DeviceResources { - var do DeviceResource - - do.Description = dr.Description - do.Name = dr.Name - do.Tag = dr.Tag - - do.Properties.Value.Type = dr.Properties.Value.Type - do.Properties.Value.ReadWrite = dr.Properties.Value.ReadWrite - do.Properties.Value.Minimum = dr.Properties.Value.Minimum - do.Properties.Value.Maximum = dr.Properties.Value.Maximum - do.Properties.Value.DefaultValue = dr.Properties.Value.DefaultValue - do.Properties.Value.Size = dr.Properties.Value.Size - do.Properties.Value.Mask = dr.Properties.Value.Mask - do.Properties.Value.Shift = dr.Properties.Value.Shift - do.Properties.Value.Scale = dr.Properties.Value.Scale - do.Properties.Value.Offset = dr.Properties.Value.Offset - do.Properties.Value.Base = dr.Properties.Value.Base - do.Properties.Value.Assertion = dr.Properties.Value.Assertion - do.Properties.Value.Precision = dr.Properties.Value.Precision - do.Properties.Value.FloatEncoding = dr.Properties.Value.FloatEncoding - do.Properties.Value.MediaType = dr.Properties.Value.MediaType - - do.Properties.Units.Type = dr.Properties.Units.Type - do.Properties.Units.ReadWrite = dr.Properties.Units.ReadWrite - do.Properties.Units.DefaultValue = dr.Properties.Units.DefaultValue - - do.Attributes = dr.Attributes - - dp.DeviceResources = append(dp.DeviceResources, do) - } - - for _, r := range from.DeviceCommands { - var pr ProfileResource - pr.Name = r.Name - for _, ro := range r.Get { - pr.Get = append(pr.Get, ResourceOperation{ - Index: ro.Index, - Operation: ro.Operation, - Object: ro.Object, - DeviceResource: ro.DeviceResource, - Parameter: ro.Parameter, - Resource: ro.Resource, - DeviceCommand: ro.DeviceCommand, - Secondary: ro.Secondary, - Mappings: ro.Mappings, - }) - } - - for _, ro := range r.Set { - pr.Set = append(pr.Set, ResourceOperation{ - Index: ro.Index, - Operation: ro.Operation, - Object: ro.Object, - DeviceResource: ro.DeviceResource, - Parameter: ro.Parameter, - Resource: ro.Resource, - DeviceCommand: ro.DeviceCommand, - Secondary: ro.Secondary, - Mappings: ro.Mappings, - }) - } - - dp.DeviceCommands = append(dp.DeviceCommands, pr) - } - - for _, command := range from.CoreCommands { - var commandModel CommandProfile - if _, err = commandModel.FromContract(command); err != nil { - return - } - dp.CoreCommands = append(dp.CoreCommands, commandModel) - } - contractId = toContractId(dp.Id, dp.Uuid) - return -} - -func (dp *DeviceProfile) TimestampForUpdate() { - dp.Modified = db.MakeTimestamp() -} - -func (dp *DeviceProfile) TimestampForAdd() { - dp.TimestampForUpdate() - dp.Created = dp.Modified -} diff --git a/internal/pkg/db/mongo/models/devicereport.go b/internal/pkg/db/mongo/models/devicereport.go deleted file mode 100644 index 9928492ef1..0000000000 --- a/internal/pkg/db/mongo/models/devicereport.go +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright 2018 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. - *******************************************************************************/ - -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" -) - -// DeviceReport -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type DeviceReport struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Name string `bson:"name"` // non-database identifier for a device report - must be unique - Device string `bson:"device"` // associated device name - should be a valid and unique device name - Action string `bson:"action"` // associated interval action name - should be a valid and unique interval action name - Expected []string `bson:"expected"` // array of value descriptor names describing the types of data captured in the report -} - -func (dr *DeviceReport) ToContract() (c contract.DeviceReport) { - // Always hand back the UUID as the contract devicereport ID unless it's blank (an old devicereport, for example blackbox test scripts) - id := dr.Uuid - if id == "" { - id = dr.Id.Hex() - } - - c.Created = dr.Created - c.Modified = dr.Modified - c.Origin = dr.Origin - c.Id = id - c.Name = dr.Name - c.Device = dr.Device - c.Action = dr.Action - c.Expected = dr.Expected - - return -} - -func (dr *DeviceReport) FromContract(from contract.DeviceReport) (id string, err error) { - if dr.Id, dr.Uuid, err = fromContractId(from.Id); err != nil { - return - } - - dr.Created = from.Created - dr.Modified = from.Modified - dr.Origin = from.Origin - dr.Name = from.Name - dr.Device = from.Device - dr.Action = from.Action - dr.Expected = from.Expected - - id = toContractId(dr.Id, dr.Uuid) - return -} - -func (dr *DeviceReport) TimestampForUpdate() { - dr.Modified = db.MakeTimestamp() -} - -func (dr *DeviceReport) TimestampForAdd() { - dr.TimestampForUpdate() - dr.Created = dr.Modified -} diff --git a/internal/pkg/db/mongo/models/deviceservice.go b/internal/pkg/db/mongo/models/deviceservice.go deleted file mode 100644 index c13fe7631b..0000000000 --- a/internal/pkg/db/mongo/models/deviceservice.go +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright 2019 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. - *******************************************************************************/ - -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo" - "github.com/globalsign/mgo/bson" -) - -type deviceServiceTransform interface { - DBRefToDeviceService(dbRef mgo.DBRef) (model DeviceService, err error) - DeviceServiceToDBRef(model DeviceService) (dbRef mgo.DBRef, err error) -} - -// DeviceService -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type DeviceService struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Description string `bson:"description"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Name string `bson:"name"` // time in milliseconds that the device last provided any feedback or responded to any request - LastConnected int64 `bson:"lastConnected"` // time in milliseconds that the device last reported data to the core - LastReported int64 `bson:"lastReported"` // operational state - either enabled or disabled - OperatingState contract.OperatingState `bson:"operatingState"` // operational state - ether enabled or disableddc - Labels []string `bson:"labels"` // tags or other labels applied to the device service for search or other identification needs - Addressable mgo.DBRef `bson:"addressable"` // address (MQTT topic, HTTP address, serial bus, etc.) for reaching the service - AdminState contract.AdminState `bson:"adminState"` // Device Service Admin State -} - -func (ds *DeviceService) ToContract(transform addressableTransform) (c contract.DeviceService, err error) { - // Always hand back the UUID as the contract command ID unless it's blank (an old command, for example blackbox test scripts) - id := ds.Uuid - if id == "" { - id = ds.Id.Hex() - } - - c.Created = ds.Created - c.Modified = ds.Modified - c.Origin = ds.Origin - c.Description = ds.Description - c.Id = id - c.Name = ds.Name - c.LastConnected = ds.LastConnected - c.LastReported = ds.LastReported - c.OperatingState = ds.OperatingState - c.Labels = ds.Labels - - aModel, err := transform.DBRefToAddressable(ds.Addressable) - if err != nil { - return contract.DeviceService{}, err - } - c.Addressable = aModel.ToContract() - c.AdminState = ds.AdminState - return -} - -func (ds *DeviceService) FromContract(from contract.DeviceService, transform addressableTransform) (id string, err error) { - ds.AdminState = from.AdminState - ds.Id, ds.Uuid, err = fromContractId(from.Id) - if err != nil { - return - } - - ds.Created = from.Created - ds.Modified = from.Modified - ds.Origin = from.Origin - ds.Description = from.Description - ds.Name = from.Name - ds.LastConnected = from.LastConnected - ds.LastReported = from.LastReported - ds.OperatingState = from.OperatingState - ds.Labels = from.Labels - - if from.Addressable.Id == "" { - byName, err := transform.GetAddressableByName(from.Addressable.Name) - if err != nil { - return "", err - } - - from.Addressable = byName - } - - var aModel Addressable - if _, err = aModel.FromContract(from.Addressable); err != nil { - return - } - if ds.Addressable, err = transform.AddressableToDBRef(aModel); err != nil { - return - } - - id = toContractId(ds.Id, ds.Uuid) - return -} - -func (s *DeviceService) TimestampForUpdate() { - s.Modified = db.MakeTimestamp() -} - -func (s *DeviceService) TimestampForAdd() { - s.TimestampForUpdate() - s.Created = s.Modified -} diff --git a/internal/pkg/db/mongo/models/event.go b/internal/pkg/db/mongo/models/event.go deleted file mode 100644 index 9bdccb86da..0000000000 --- a/internal/pkg/db/mongo/models/event.go +++ /dev/null @@ -1,103 +0,0 @@ -/******************************************************************************* - * Copyright 2018 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. - *******************************************************************************/ -package models - -import ( - correlation "github.com/edgexfoundry/edgex-go/internal/pkg/correlation/models" - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - - "github.com/globalsign/mgo" - "github.com/globalsign/mgo/bson" - "github.com/pkg/errors" -) - -// Event -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Event struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Pushed int64 `bson:"pushed"` - Device string `bson:"device"` // Device identifier (name or id) - Readings []mgo.DBRef `bson:"readings,omitempty"` // List of readings - Checksum string `bson:"checksum,omitempty"` // checksum used to identify events -} - -func (e *Event) ToContract(transform readingTransform) (c contract.Event, err error) { - id := e.Uuid - if id == "" { - id = e.Id.Hex() - } - - c.ID = id - c.Created = e.Created - c.Modified = e.Modified - c.Origin = e.Origin - c.Pushed = e.Pushed - c.Device = e.Device - - c.Readings = []contract.Reading{} - for _, dbRef := range e.Readings { - var r Reading - if r, err = transform.DBRefToReading(dbRef); err != nil { - return contract.Event{}, err - } - c.Readings = append(c.Readings, r.ToContract()) - } - return -} - -func (e *Event) FromContract(from correlation.Event, transform readingTransform) (id string, err error) { - e.Id, e.Uuid, err = fromContractId(from.ID) - if err != nil { - return - } - - e.Created = from.Created - e.Modified = from.Modified - e.Origin = from.Origin - e.Pushed = from.Pushed - e.Device = from.Device - e.Checksum = from.Checksum - - e.Readings = []mgo.DBRef{} - for _, reading := range from.Readings { - var readingModel Reading - if rid, err := readingModel.FromContract(reading); err != nil { - return "", errors.New(err.Error() + " id: " + rid) - } - - var dbRef mgo.DBRef - if dbRef, err = transform.ReadingToDBRef(readingModel); err != nil { - return - } - e.Readings = append(e.Readings, dbRef) - } - - id = toContractId(e.Id, e.Uuid) - return -} - -func (e *Event) TimestampForUpdate() { - e.Modified = db.MakeTimestamp() -} - -func (e *Event) TimestampForAdd() { - e.TimestampForUpdate() - e.Created = e.Modified -} diff --git a/internal/pkg/db/mongo/models/id.go b/internal/pkg/db/mongo/models/id.go deleted file mode 100644 index 96d4cf258f..0000000000 --- a/internal/pkg/db/mongo/models/id.go +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright 2019 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. - *******************************************************************************/ - -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - "github.com/globalsign/mgo/bson" - "github.com/google/uuid" -) - -func fromContractId(id string) (bson.ObjectId, string, error) { - // In this first case, ID is empty so this must be an add. - // Generate new BSON/UUIDs - if id == "" { - return bson.NewObjectId(), uuid.New().String(), nil - } - - // In this case, we're dealing with an existing id - if !bson.IsObjectIdHex(id) { - // Id is not a BSON ID. Is it a UUID? - _, err := uuid.Parse(id) - if err != nil { // It is some unsupported type of string - return "", "", db.ErrInvalidObjectId - } - return "", id, nil - } - - // ID of pre-existing event is a BSON ID. We will query using the BSON ID. - return bson.ObjectIdHex(id), "", nil -} - -func toContractId(id bson.ObjectId, uuid string) string { - if uuid != "" { - return uuid - } - - return id.Hex() -} diff --git a/internal/pkg/db/mongo/models/interval.go b/internal/pkg/db/mongo/models/interval.go deleted file mode 100644 index c63b00e87e..0000000000 --- a/internal/pkg/db/mongo/models/interval.go +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright 2019 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. - *******************************************************************************/ - -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" -) - -// Interval -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Interval struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Name string `bson:"name"` - Start string `bson:"start"` - End string `bson:"end"` - Frequency string `bson:"frequency"` - Cron string `bson:"cron,omitempty"` - RunOnce bool `bson:"runonce"` -} - -func (in *Interval) ToContract() (c contract.Interval) { - // Always hand back the UUID as the contract event ID unless it'in blank (an old event, for example blackbox test scripts - id := in.Uuid - if id == "" { - id = in.Id.Hex() - } - - c.Timestamps = contract.Timestamps{Created: in.Created, Modified: in.Modified, Origin: in.Origin} - c.ID = id - c.Name = in.Name - c.Start = in.Start - c.End = in.End - c.Frequency = in.Frequency - c.Cron = in.Cron - c.RunOnce = in.RunOnce - return -} - -func (in *Interval) FromContract(from contract.Interval) (id string, err error) { - in.Id, in.Uuid, err = fromContractId(from.ID) - if err != nil { - return - } - - in.Created = from.Timestamps.Created - in.Modified = from.Timestamps.Modified - in.Origin = from.Timestamps.Origin - in.Name = from.Name - in.Start = from.Start - in.End = from.End - in.Frequency = from.Frequency - in.RunOnce = from.RunOnce - in.Cron = from.Cron - - id = toContractId(in.Id, in.Uuid) - return -} - -func (in *Interval) TimestampForUpdate() { - in.Modified = db.MakeTimestamp() -} - -func (in *Interval) TimestampForAdd() { - in.TimestampForUpdate() - in.Created = in.Modified -} diff --git a/internal/pkg/db/mongo/models/interval_action.go b/internal/pkg/db/mongo/models/interval_action.go deleted file mode 100644 index 21f421660d..0000000000 --- a/internal/pkg/db/mongo/models/interval_action.go +++ /dev/null @@ -1,95 +0,0 @@ -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" -) - -// IntervalAction -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type IntervalAction struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Name string `bson:"name"` - Interval string `bson:"interval"` - Parameters string `bson:"parameters"` - Target string `bson:"target"` - Protocol string `bson:"protocol"` - HTTPMethod string `bson:"httpMethod"` - Address string `bson:"address"` - Port int `bson:"port"` - Path string `bson:"path"` - Publisher string `bson:"publisher"` - User string `bson:"user"` - Password string `bson:"password"` - Topic string `bson:"topic"` -} - -func (ia *IntervalAction) ToContract() (c contract.IntervalAction) { - // Always hand back the UUID as the contract event ID unless it's blank (an old event, for example blackbox test scripts - id := ia.Uuid - if id == "" { - id = ia.Id.Hex() - } - - c.ID = id - c.Created = ia.Created - c.Modified = ia.Modified - c.Origin = ia.Origin - c.Name = ia.Name - c.Interval = ia.Interval - c.Parameters = ia.Parameters - c.Target = ia.Target - c.Protocol = ia.Protocol - c.HTTPMethod = ia.HTTPMethod - c.Address = ia.Address - c.Port = ia.Port - c.Path = ia.Path - c.Publisher = ia.Publisher - c.User = ia.User - c.Password = ia.Password - c.Topic = ia.Topic - - return -} - -func (ia *IntervalAction) FromContract(from contract.IntervalAction) (id string, err error) { - ia.Id, ia.Uuid, err = fromContractId(from.ID) - if err != nil { - return - } - - ia.Created = from.Created - ia.Modified = from.Modified - ia.Origin = from.Origin - ia.Name = from.Name - ia.Interval = from.Interval - ia.Parameters = from.Parameters - ia.Target = from.Target - ia.Protocol = from.Protocol - ia.HTTPMethod = from.HTTPMethod - ia.Address = from.Address - ia.Port = from.Port - ia.Path = from.Path - ia.Publisher = from.Publisher - ia.User = from.User - ia.Password = from.Password - ia.Topic = from.Topic - - id = toContractId(ia.Id, ia.Uuid) - return -} - -func (ia *IntervalAction) TimestampForUpdate() { - ia.Modified = db.MakeTimestamp() -} - -func (ia *IntervalAction) TimestampForAdd() { - ia.TimestampForUpdate() - ia.Created = ia.Modified -} diff --git a/internal/pkg/db/mongo/models/notification.go b/internal/pkg/db/mongo/models/notification.go deleted file mode 100644 index 557f2d87cf..0000000000 --- a/internal/pkg/db/mongo/models/notification.go +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies 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. - * - *******************************************************************************/ - -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" -) - -// Notification -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Notification struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Slug string `bson:"slug"` - Sender string `bson:"sender"` - Category contract.NotificationsCategory `bson:"category"` - Severity contract.NotificationsSeverity `bson:"severity"` - Content string `bson:"content"` - Description string `bson:"description"` - Status contract.NotificationsStatus `bson:"status"` - Labels []string `bson:"labels,omitempty"` - ContentType string `bson:"contenttype"` -} - -func (n *Notification) ToContract() (c contract.Notification) { - id := n.Uuid - if id == "" { - id = n.Id.Hex() - } - - c.ID = id - c.Created = n.Created - c.Modified = n.Modified - c.Origin = n.Origin - c.Slug = n.Slug - c.Sender = n.Sender - c.Category = n.Category - c.Severity = n.Severity - c.Content = n.Content - c.Description = n.Description - c.Status = n.Status - c.Labels = n.Labels - c.ContentType = n.ContentType - - return -} - -func (n *Notification) FromContract(from contract.Notification) (id string, err error) { - n.Id, n.Uuid, err = fromContractId(from.ID) - if err != nil { - return - } - - n.Created = from.Created - n.Modified = from.Modified - n.Origin = from.Origin - n.Slug = from.Slug - n.Sender = from.Sender - n.Category = from.Category - n.Severity = from.Severity - n.Content = from.Content - n.Description = from.Description - n.Status = from.Status - n.Labels = from.Labels - n.ContentType = from.ContentType - - id = toContractId(n.Id, n.Uuid) - return -} - -func (n *Notification) TimestampForUpdate() { - n.Modified = db.MakeTimestamp() -} - -func (n *Notification) TimestampForAdd() { - n.TimestampForUpdate() - n.Created = n.Modified -} diff --git a/internal/pkg/db/mongo/models/provisionwatcher.go b/internal/pkg/db/mongo/models/provisionwatcher.go deleted file mode 100644 index 23cf08b593..0000000000 --- a/internal/pkg/db/mongo/models/provisionwatcher.go +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright 2019 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. - *******************************************************************************/ - -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo" - "github.com/globalsign/mgo/bson" -) - -// ProvisionWatcher -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type ProvisionWatcher struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Name string `bson:"name"` // unique name and identifier of the addressable - Identifiers map[string]string `bson:"identifiers"` // set of key value pairs that identify type of of address (MAC, HTTP,...) and address to watch for (00-05-1B-A1-99-99, 10.0.0.1,...) - BlockingIdentifiers map[string][]string `bson:"blockingidentifiers"` // set of keys and blocking values that disallow matches made on Identifiers - Profile mgo.DBRef `bson:"profile"` // device profile that should be applied to the devices available at the identifier addresses - Service mgo.DBRef `bson:"service"` // device service that owns the watcher - OperatingState contract.OperatingState `bson:"operatingState"` // operational state - either enabled or disabled - AdminState contract.AdminState `bson:"adminState"` // administrative state - either unlocked or locked -} - -func (pw *ProvisionWatcher) ToContract(dpt deviceProfileTransform, dst deviceServiceTransform, at addressableTransform) (c contract.ProvisionWatcher, err error) { - id := pw.Uuid - if id == "" { - id = pw.Id.Hex() - } - - c.Id = id - c.Created = pw.Created - c.Modified = pw.Modified - c.Origin = pw.Origin - c.Name = pw.Name - c.Identifiers = pw.Identifiers - c.BlockingIdentifiers = pw.BlockingIdentifiers - - profile, err := dpt.DBRefToDeviceProfile(pw.Profile) - if err != nil { - return contract.ProvisionWatcher{}, err - } - c.Profile, err = profile.ToContract() - if err != nil { - return contract.ProvisionWatcher{}, err - } - - service, err := dst.DBRefToDeviceService(pw.Service) - if err != nil { - return contract.ProvisionWatcher{}, err - } - c.Service, err = service.ToContract(at) - if err != nil { - return contract.ProvisionWatcher{}, err - } - - c.OperatingState = pw.OperatingState - c.AdminState = pw.AdminState - - return -} - -func (pw *ProvisionWatcher) FromContract( - from contract.ProvisionWatcher, - dpt deviceProfileTransform, - dst deviceServiceTransform, - at addressableTransform) (id string, err error) { - - pw.Id, pw.Uuid, err = fromContractId(from.Id) - if err != nil { - return - } - - pw.Created = from.Created - pw.Modified = from.Modified - pw.Origin = from.Origin - pw.Name = from.Name - pw.Identifiers = from.Identifiers - pw.BlockingIdentifiers = from.BlockingIdentifiers - - var profile DeviceProfile - if _, err = profile.FromContract(from.Profile); err != nil { - return - } - if pw.Profile, err = dpt.DeviceProfileToDBRef(profile); err != nil { - return - } - - var service DeviceService - if _, err = service.FromContract(from.Service, at); err != nil { - return - } - if pw.Service, err = dst.DeviceServiceToDBRef(service); err != nil { - return - } - - pw.OperatingState = from.OperatingState - pw.AdminState = from.AdminState - - id = toContractId(pw.Id, pw.Uuid) - return -} - -func (pw *ProvisionWatcher) TimestampForUpdate() { - pw.Modified = db.MakeTimestamp() -} - -func (pw *ProvisionWatcher) TimestampForAdd() { - pw.TimestampForUpdate() - pw.Created = pw.Modified -} diff --git a/internal/pkg/db/mongo/models/reading.go b/internal/pkg/db/mongo/models/reading.go deleted file mode 100644 index 00bd644db2..0000000000 --- a/internal/pkg/db/mongo/models/reading.go +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * Copyright 2018 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. - *******************************************************************************/ -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo" - "github.com/globalsign/mgo/bson" -) - -type readingTransform interface { - DBRefToReading(dbRef mgo.DBRef) (a Reading, err error) - ReadingToDBRef(a Reading) (dbRef mgo.DBRef, err error) -} - -// Reading -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Reading struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid"` - Pushed int64 `bson:"pushed"` // When the data was pushed out of EdgeX (0 - not pushed yet) - Device string `bson:"device"` - Name string `bson:"name"` - Value string `bson:"value"` // Device sensor data value - ValueType string `bson:"valueType"` - MediaType string `bson:"mediaType"` - FloatEncoding string `bson:"floatEncoding"` -} - -func (r *Reading) ToContract() (c contract.Reading) { - // Always hand back the UUID as the contract event ID unless it's blank (an old event, for example blackbox test scripts) - id := r.Uuid - if id == "" { - id = r.Id.Hex() - } - - c.Id = id - c.Created = r.Created - c.Modified = r.Modified - c.Origin = r.Origin - c.Pushed = r.Pushed - c.Device = r.Device - c.Name = r.Name - c.Value = r.Value - c.ValueType = r.ValueType - c.MediaType = r.MediaType - c.FloatEncoding = r.FloatEncoding - - return c -} - -func (r *Reading) FromContract(from contract.Reading) (id string, err error) { - r.Id, r.Uuid, err = fromContractId(from.Id) - if err != nil { - return - } - - r.Created = from.Created - r.Modified = from.Modified - r.Origin = from.Origin - r.Pushed = from.Pushed - r.Device = from.Device - r.Name = from.Name - r.Value = from.Value - r.ValueType = from.ValueType - r.MediaType = from.MediaType - r.FloatEncoding = from.FloatEncoding - - id = toContractId(r.Id, r.Uuid) - return -} - -func (r *Reading) TimestampForUpdate() { - r.Modified = db.MakeTimestamp() -} - -func (r *Reading) TimestampForAdd() { - r.TimestampForUpdate() - r.Created = r.Modified -} diff --git a/internal/pkg/db/mongo/models/subscription.go b/internal/pkg/db/mongo/models/subscription.go deleted file mode 100644 index 428aafa0d0..0000000000 --- a/internal/pkg/db/mongo/models/subscription.go +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies 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. - * - *******************************************************************************/ - -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - - "github.com/globalsign/mgo/bson" -) - -// Subscription -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Subscription struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Slug string `bson:"slug"` - Receiver string `bson:"receiver"` - Description string `bson:"description"` - SubscribedCategories []contract.NotificationsCategory `bson:"subscribedCategories,omitempty"` - SubscribedLabels []string `bson:"subscribedLabels,omitempty"` - Channels []Channel `bson:"channels,omitempty"` -} - -func (s *Subscription) ToContract() (c contract.Subscription) { - id := s.Uuid - if id == "" { - id = s.Id.Hex() - } - - c.ID = id - c.Created = s.Created - c.Modified = s.Modified - c.Origin = s.Origin - c.Slug = s.Slug - c.Receiver = s.Receiver - c.Description = s.Description - c.SubscribedCategories = s.SubscribedCategories - c.SubscribedLabels = s.SubscribedLabels - - for _, channel := range s.Channels { - c.Channels = append(c.Channels, channel.ToContract()) - } - - return -} - -func (s *Subscription) FromContract(from contract.Subscription) (id string, err error) { - s.Id, s.Uuid, err = fromContractId(from.ID) - if err != nil { - return - } - - s.Created = from.Created - s.Modified = from.Modified - s.Origin = from.Origin - s.Slug = from.Slug - s.Receiver = from.Receiver - s.Description = from.Description - s.SubscribedCategories = from.SubscribedCategories - s.SubscribedLabels = from.SubscribedLabels - - for _, channel := range from.Channels { - var model Channel - model.FromContract(channel) - s.Channels = append(s.Channels, model) - } - - id = toContractId(s.Id, s.Uuid) - return -} - -func (s *Subscription) TimestampForUpdate() { - s.Modified = db.MakeTimestamp() -} - -func (s *Subscription) TimestampForAdd() { - s.TimestampForUpdate() - s.Created = s.Modified -} diff --git a/internal/pkg/db/mongo/models/transmission.go b/internal/pkg/db/mongo/models/transmission.go deleted file mode 100644 index c1f4e2a29d..0000000000 --- a/internal/pkg/db/mongo/models/transmission.go +++ /dev/null @@ -1,110 +0,0 @@ -/******************************************************************************* - * Copyright 2019 Dell Technologies 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. - * - *******************************************************************************/ - -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" -) - -type TransmissionRecord struct { - Status contract.TransmissionStatus `bson:"status"` - Response string `bson:"response"` - Sent int64 `bson:"sent"` -} - -// Transmission -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type Transmission struct { - Created int64 `bson:"created"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid,omitempty"` - Notification Notification `bson:"notification,omitempty"` - Receiver string `bson:"receiver"` - Channel Channel `bson:"channel,omitempty"` - Status contract.TransmissionStatus `bson:"status"` - ResendCount int `bson:"resendcount"` - Records []TransmissionRecord `bson:"records,omitempty"` -} - -func (t *Transmission) ToContract() (c contract.Transmission) { - id := t.Uuid - if id == "" { - id = t.Id.Hex() - } - - c.ID = id - c.Created = t.Created - c.Modified = t.Modified - c.Origin = t.Origin - c.Notification = t.Notification.ToContract() - c.Receiver = t.Receiver - c.Channel = t.Channel.ToContract() - c.Status = t.Status - c.ResendCount = t.ResendCount - - for _, record := range t.Records { - c.Records = append(c.Records, contract.TransmissionRecord{ - Status: record.Status, - Response: record.Response, - Sent: record.Sent, - }) - } - - return -} - -func (t *Transmission) FromContract(from contract.Transmission) (id string, err error) { - t.Id, t.Uuid, err = fromContractId(from.ID) - if err != nil { - return - } - - t.Created = from.Created - t.Modified = from.Modified - t.Origin = from.Origin - if _, err = t.Notification.FromContract(from.Notification); err != nil { - return - } - t.Receiver = from.Receiver - t.Channel.FromContract(from.Channel) - t.Status = from.Status - t.ResendCount = from.ResendCount - - for _, record := range from.Records { - t.Records = append(t.Records, TransmissionRecord{ - Status: record.Status, - Response: record.Response, - Sent: record.Sent, - }) - } - - id = toContractId(t.Id, t.Uuid) - return -} - -func (t *Transmission) TimestampForUpdate() { - t.Modified = db.MakeTimestamp() -} - -func (t *Transmission) TimestampForAdd() { - t.TimestampForUpdate() - t.Created = t.Modified -} diff --git a/internal/pkg/db/mongo/models/value_descriptor.go b/internal/pkg/db/mongo/models/value_descriptor.go deleted file mode 100644 index 2bf5aa002b..0000000000 --- a/internal/pkg/db/mongo/models/value_descriptor.go +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright 2018 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. - *******************************************************************************/ -package models - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" -) - -// ValueDescriptor -// -// Deprecated: Mongo functionality is deprecated as of the Geneva release. -type ValueDescriptor struct { - Id bson.ObjectId `bson:"_id,omitempty"` - Uuid string `bson:"uuid"` - Created int64 `bson:"created"` - Description string `bson:"description,omitempty"` - Modified int64 `bson:"modified"` - Origin int64 `bson:"origin"` - Name string `bson:"name"` - Min interface{} `bson:"min,omitempty"` - Max interface{} `bson:"max,omitempty"` - DefaultValue interface{} `bson:"defaultValue,omitempty"` - Type string `bson:"type,omitempty"` - UomLabel string `bson:"uomLabel,omitempty"` - Formatting string `bson:"formatting,omitempty"` - Labels []string `bson:"labels,omitempty"` - MediaType string `bson:"mediaType,omitempty"` - FloatEncoding string `bson:"floatEncoding,omitempty"` -} - -func (v *ValueDescriptor) ToContract() contract.ValueDescriptor { - // Always hand back the UUID as the contract event ID unless it's blank (an old event, for example blackbox test scripts) - id := v.Uuid - if id == "" { - id = v.Id.Hex() - } - to := contract.ValueDescriptor{ - Id: id, - Created: v.Created, - Description: v.Description, - Modified: v.Modified, - Origin: v.Origin, - Name: v.Name, - Min: v.Min, - Max: v.Max, - DefaultValue: v.DefaultValue, - Type: v.Type, - UomLabel: v.UomLabel, - Formatting: v.Formatting, - Labels: []string{}, - MediaType: v.MediaType, - FloatEncoding: v.FloatEncoding, - } - for _, l := range v.Labels { - to.Labels = append(to.Labels, l) - } - return to -} - -func (v *ValueDescriptor) FromContract(from contract.ValueDescriptor) (id string, err error) { - v.Id, v.Uuid, err = fromContractId(from.Id) - if err != nil { - return - } - - v.Created = from.Created - v.Description = from.Description - v.Modified = from.Modified - v.Origin = from.Origin - v.Name = from.Name - v.Min = from.Min - v.Max = from.Max - v.DefaultValue = from.DefaultValue - v.Type = from.Type - v.UomLabel = from.UomLabel - v.Formatting = from.Formatting - v.Labels = []string{} - v.MediaType = from.MediaType - v.FloatEncoding = from.FloatEncoding - - for _, l := range from.Labels { - v.Labels = append(v.Labels, l) - } - - if v.Created == 0 { - v.Created = db.MakeTimestamp() - } - - id = toContractId(v.Id, v.Uuid) - return -} diff --git a/internal/pkg/db/mongo/notifications.go b/internal/pkg/db/mongo/notifications.go deleted file mode 100644 index 6ef3cadb5e..0000000000 --- a/internal/pkg/db/mongo/notifications.go +++ /dev/null @@ -1,482 +0,0 @@ -/******************************************************************************* - * Copyright 2018 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. - * - *******************************************************************************/ - -package mongo - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - "github.com/edgexfoundry/edgex-go/internal/pkg/db/mongo/models" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" -) - -const ( - NOTIFICATION_COLLECTION = "notification" - SUBSCRIPTION_COLLECTION = "subscription" - TRANSMISSION_COLLECTION = "transmission" -) - -var currentMaxResultCount int // configuration read max limit -var cleanupDefaultAge int - -/* ----------------------- Notifications ------------------------*/ - -func (mc MongoClient) GetNotifications() ([]contract.Notification, error) { - return mc.getNotifications(bson.M{}) -} - -func (mc MongoClient) GetNotificationById(id string) (contract.Notification, error) { - query, err := idToBsonM(id) - if err != nil { - return contract.Notification{}, err - } - return mc.getNotification(query) -} - -func (mc MongoClient) GetNotificationBySlug(slug string) (contract.Notification, error) { - return mc.getNotification(bson.M{"slug": slug}) -} - -func (mc MongoClient) GetNotificationBySender(sender string, limit int) ([]contract.Notification, error) { - return mc.getNotificationsLimit(bson.M{"sender": sender}, limit) -} - -func (mc MongoClient) GetNotificationsByLabels(labels []string, limit int) ([]contract.Notification, error) { - return mc.getNotificationsLimit(bson.M{"labels": bson.M{"$in": labels}}, limit) -} - -func (mc MongoClient) GetNotificationsByStartEnd(start int64, end int64, limit int) ([]contract.Notification, error) { - return mc.getNotificationsLimit(bson.M{"created": bson.M{"$gt": start, "$lt": end}}, limit) -} - -func (mc MongoClient) GetNotificationsByStart(start int64, limit int) ([]contract.Notification, error) { - return mc.getNotificationsLimit(bson.M{"created": bson.M{"$gt": start}}, limit) -} - -func (mc MongoClient) GetNotificationsByEnd(end int64, limit int) ([]contract.Notification, error) { - return mc.getNotificationsLimit(bson.M{"created": bson.M{"$lt": end}}, limit) -} - -func (mc MongoClient) GetNewNotifications(limit int) ([]contract.Notification, error) { - return mc.getNotificationsLimit(bson.M{"status": "NEW"}, limit) -} - -func (mc MongoClient) GetNewNormalNotifications(limit int) ([]contract.Notification, error) { - return mc.getNotificationsLimit(bson.M{"status": "NEW", "severity": "NORMAL"}, limit) -} - -func (mc MongoClient) AddNotification(n contract.Notification) (string, error) { - s := mc.getSessionCopy() - defer s.Close() - - var mapped models.Notification - id, err := mapped.FromContract(n) - if err != nil { - return "", err - } - - if err = mc.checkNotificationSlugIntegrity(mapped.Slug); err != nil { - return "", err - } - - mapped.TimestampForAdd() - - if err = s.DB(mc.database.Name).C(NOTIFICATION_COLLECTION).Insert(mapped); err != nil { - return "", errorMap(err) - } - - return id, err -} - -func (mc MongoClient) UpdateNotification(n contract.Notification) error { - return mc.updateNotification(n) -} - -func (mc MongoClient) MarkNotificationProcessed(n contract.Notification) error { - n.Status = contract.NotificationsStatus(contract.Processed) - return mc.updateNotification(n) -} - -func (mc MongoClient) DeleteNotificationById(id string) error { - mn, err := mc.GetNotificationById(id) - if err == db.ErrNotFound { - return err - } - return mc.deleteNotificationAndAssociatedTransmissions(mn) -} - -func (mc MongoClient) DeleteNotificationBySlug(slug string) error { - mn, err := mc.GetNotificationBySlug(slug) - if err == db.ErrNotFound { - return err - } - return mc.deleteNotificationAndAssociatedTransmissions(mn) -} - -func (mc MongoClient) DeleteNotificationsOld(age int) error { - currentTime := db.MakeTimestamp() - end := int(currentTime) - age - query := bson.M{"modified": bson.M{ - "$lt": end}, "status": "PROCESSED"} - mns, err := mc.getNotifications(query) - if err == db.ErrNotFound { - return err - } - for _, mn := range mns { - if err := mc.deleteNotificationAndAssociatedTransmissions(mn); err != nil { - return err - } - } - return nil -} - -func (mc MongoClient) deleteNotificationAndAssociatedTransmissions(n contract.Notification) error { - if err := mc.deleteAll(bson.M{"notification.slug": n.Slug}, TRANSMISSION_COLLECTION); err != nil { - return err - } - - return mc.deleteByObjectID(n.ID, NOTIFICATION_COLLECTION) -} - -func (mc MongoClient) checkNotificationSlugIntegrity(slug string) error { - if slug == "" { - return db.ErrSlugEmpty - } - - if _, err := mc.getNotification(bson.M{"slug": slug}); err == nil { - return db.ErrNotUnique - } - return nil -} - -func (mc MongoClient) updateNotification(n contract.Notification) error { - var mapped models.Notification - id, err := mapped.FromContract(n) - if err != nil { - return err - } - - mapped.TimestampForUpdate() - - return mc.updateId(NOTIFICATION_COLLECTION, id, mapped) -} - -func (mc MongoClient) getNotification(q bson.M) (contract.Notification, error) { - s := mc.getSessionCopy() - defer s.Close() - - var model models.Notification - if err := errorMap(s.DB(mc.database.Name).C(NOTIFICATION_COLLECTION).Find(q).One(&model)); err == db.ErrNotFound { - return contract.Notification{}, err - } - - return model.ToContract(), nil -} - -func (mc MongoClient) getNotifications(q bson.M) ([]contract.Notification, error) { - return mc.getNotificationsLimit(q, currentMaxResultCount) -} - -func (mc MongoClient) getNotificationsLimit(q bson.M, limit int) ([]contract.Notification, error) { - s := mc.getSessionCopy() - defer s.Close() - - // Check if limit is 0 - if limit == 0 { - return []contract.Notification{}, nil - } - - var notifications []models.Notification - if err := s.DB(mc.database.Name).C(NOTIFICATION_COLLECTION).Find(q).Limit(limit).All(¬ifications); err != nil { - return []contract.Notification{}, errorMap(err) - } - - contracts := []contract.Notification{} - for _, model := range notifications { - contracts = append(contracts, model.ToContract()) - } - return contracts, nil -} - -/* ----------------------- Subscriptions ------------------------*/ - -func (mc MongoClient) GetSubscriptionBySlug(slug string) (contract.Subscription, error) { - return mc.getSubscription(bson.M{"slug": slug}) -} - -func (mc MongoClient) GetSubscriptionByCategories(categories []string) ([]contract.Subscription, error) { - return mc.getSubscriptions(bson.M{"subscribedCategories": bson.M{"$in": categories}}) -} - -func (mc MongoClient) GetSubscriptionByLabels(labels []string) ([]contract.Subscription, error) { - return mc.getSubscriptions(bson.M{"subscribedLabels": bson.M{"$in": labels}}) -} - -func (mc MongoClient) GetSubscriptionByCategoriesLabels(categories []string, labels []string) ([]contract.Subscription, error) { - return mc.getSubscriptions(bson.M{"subscribedCategories": bson.M{"$in": categories}, "subscribedLabels": bson.M{"$in": labels}}) -} - -func (mc MongoClient) GetSubscriptionByReceiver(receiver string) ([]contract.Subscription, error) { - return mc.getSubscriptions(bson.M{"receiver": receiver}) -} - -func (mc MongoClient) GetSubscriptionById(id string) (contract.Subscription, error) { - query, err := idToBsonM(id) - if err != nil { - return contract.Subscription{}, err - } - return mc.getSubscription(query) -} - -func (mc MongoClient) DeleteSubscriptionById(id string) error { - return mc.deleteByObjectID(id, SUBSCRIPTION_COLLECTION) -} - -func (mc MongoClient) AddSubscription(sub contract.Subscription) (string, error) { - s := mc.getSessionCopy() - defer s.Close() - - var mapped models.Subscription - id, err := mapped.FromContract(sub) - if err != nil { - return "", err - } - - if err = mc.checkSubscriptionSlugIntegrity(mapped.Slug); err != nil { - return "", err - } - - mapped.TimestampForAdd() - - if err = s.DB(mc.database.Name).C(SUBSCRIPTION_COLLECTION).Insert(mapped); err != nil { - return "", errorMap(err) - } - - return id, nil -} - -func (mc MongoClient) UpdateSubscription(sub contract.Subscription) error { - var mapped models.Subscription - id, err := mapped.FromContract(sub) - if err != nil { - return err - } - - mapped.TimestampForUpdate() - - return mc.updateId(SUBSCRIPTION_COLLECTION, id, mapped) -} - -func (mc MongoClient) DeleteSubscriptionBySlug(slug string) error { - ms, err := mc.GetSubscriptionBySlug(slug) - if err == db.ErrNotFound { - return err - } - return mc.deleteByObjectID(ms.ID, SUBSCRIPTION_COLLECTION) -} - -// Return all the subscriptions -// UnexpectedError - failed to retrieve subscriptions from the database -func (mc MongoClient) GetSubscriptions() ([]contract.Subscription, error) { - return mc.getSubscriptions(bson.M{}) -} - -func (mc MongoClient) checkSubscriptionSlugIntegrity(slug string) error { - if slug == "" { - return db.ErrSlugEmpty - } - _, err := mc.getSubscription(bson.M{"slug": slug}) - if err == nil { - return db.ErrNotUnique - } - return nil -} - -func (mc MongoClient) getSubscription(q bson.M) (c contract.Subscription, err error) { - s := mc.getSessionCopy() - defer s.Close() - - var sub models.Subscription - if err = s.DB(mc.database.Name).C(SUBSCRIPTION_COLLECTION).Find(q).One(&sub); err != nil { - return c, errorMap(err) - } - c = sub.ToContract() - return -} - -func (mc MongoClient) getSubscriptions(q bson.M) (c []contract.Subscription, err error) { - s := mc.getSessionCopy() - defer s.Close() - - var subs []models.Subscription - if err = errorMap(s.DB(mc.database.Name).C(SUBSCRIPTION_COLLECTION).Find(q).All(&subs)); err != nil { - return - } - - c = []contract.Subscription{} - for _, sub := range subs { - c = append(c, sub.ToContract()) - } - return -} - -/* ----------------------- Transmissions ------------------------*/ - -// limits for transmissions here refer to resend counts - -func (mc MongoClient) AddTransmission(t contract.Transmission) (string, error) { - s := mc.getSessionCopy() - defer s.Close() - - var mapped models.Transmission - id, err := mapped.FromContract(t) - if err != nil { - return "", err - } - - mapped.TimestampForAdd() - - if err = s.DB(mc.database.Name).C(TRANSMISSION_COLLECTION).Insert(mapped); err != nil { - return "", errorMap(err) - } - - return id, nil -} - -func (mc MongoClient) UpdateTransmission(t contract.Transmission) error { - var mapped models.Transmission - id, err := mapped.FromContract(t) - if err != nil { - return err - } - - mapped.TimestampForUpdate() - - return mc.updateId(TRANSMISSION_COLLECTION, id, mapped) -} - -func (mc MongoClient) DeleteTransmission(age int64, status contract.TransmissionStatus) error { - currentTime := db.MakeTimestamp() - end := currentTime - age - return mc.deleteAll(bson.M{"modified": bson.M{"$lt": end}, "status": status}, TRANSMISSION_COLLECTION) -} - -func (mc MongoClient) GetTransmissionById(id string) (contract.Transmission, error) { - query, err := idToBsonM(id) - if err != nil { - return contract.Transmission{}, err - } - return mc.getTransmission(query) -} - -func (mc MongoClient) GetTransmissionsByNotificationSlug(slug string, limit int) ([]contract.Transmission, error) { - return mc.getTransmissionsLimit(bson.M{"notification.slug": slug}, limit) -} - -func (mc MongoClient) GetTransmissionsByNotificationSlugAndStartEnd(slug string, start int64, end int64, limit int) ([]contract.Transmission, error) { - return mc.getTransmissionsLimit(bson.M{"notification.slug": slug, "created": bson.M{"$gt": start, "$lt": end}}, limit) -} - -func (mc MongoClient) GetTransmissionsByStartEnd(start int64, end int64, limit int) ([]contract.Transmission, error) { - return mc.getTransmissionsLimit(bson.M{"created": bson.M{"$gt": start, "$lt": end}}, limit) -} - -func (mc MongoClient) GetTransmissionsByStart(start int64, limit int) ([]contract.Transmission, error) { - return mc.getTransmissionsLimit(bson.M{"created": bson.M{"$gt": start}}, limit) -} - -func (mc MongoClient) GetTransmissionsByEnd(end int64, limit int) ([]contract.Transmission, error) { - return mc.getTransmissionsLimit(bson.M{"created": bson.M{"$lt": end}}, limit) -} - -func (mc MongoClient) GetTransmissionsByStatus(limit int, status contract.TransmissionStatus) ([]contract.Transmission, error) { - return mc.getTransmissionsLimit(bson.M{"status": status}, limit) -} - -func (mc MongoClient) getTransmission(q bson.M) (c contract.Transmission, err error) { - s := mc.getSessionCopy() - defer s.Close() - - var t models.Transmission - if err = errorMap(s.DB(mc.database.Name).C(TRANSMISSION_COLLECTION).Find(q).One(&t)); err != nil { - return - } - c = t.ToContract() - return -} - -func (mc MongoClient) getTransmissionsLimit(q bson.M, limit int) (c []contract.Transmission, err error) { - s := mc.getSessionCopy() - defer s.Close() - - if limit == 0 { - return []contract.Transmission{}, nil - } - - var transmissions []models.Transmission - if err = errorMap(s.DB(mc.database.Name).C(TRANSMISSION_COLLECTION).Find(q).Limit(limit).All(&transmissions)); err != nil { - return - } - - c = []contract.Transmission{} - for _, transmission := range transmissions { - c = append(c, transmission.ToContract()) - } - return -} - -/* ----------------------- General Deletion ------------------------*/ - -func (mc MongoClient) deleteByObjectID(id string, col string) (err error) { - s := mc.getSessionCopy() - defer s.Close() - - query, err := idToBsonM(id) - if err != nil { - return - } - return errorMap(s.DB(mc.database.Name).C(col).Remove(query)) -} - -func (mc MongoClient) deleteAll(q bson.M, col string) error { - s := mc.getSessionCopy() - defer s.Close() - - _, err := s.DB(mc.database.Name).C(col).RemoveAll(q) - return errorMap(err) -} - -/* ----------------------- General Cleanup ------------------------*/ - -func (mc MongoClient) Cleanup() error { - return mc.CleanupOld(cleanupDefaultAge) -} - -func (mc MongoClient) CleanupOld(age int) error { - currentTime := db.MakeTimestamp() - end := int(currentTime) - age - query := bson.M{"modified": bson.M{"$lt": end}} - mns, err := mc.getNotifications(query) - if err == db.ErrNotFound { - return err - } - for _, mn := range mns { - err = mc.deleteNotificationAndAssociatedTransmissions(mn) - if err != nil { - return err - } - } - return nil -} diff --git a/internal/pkg/db/mongo/scheduler.go b/internal/pkg/db/mongo/scheduler.go deleted file mode 100644 index 19f60d5fb9..0000000000 --- a/internal/pkg/db/mongo/scheduler.go +++ /dev/null @@ -1,365 +0,0 @@ -/******************************************************************************* - * Copyright 2018 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. - *******************************************************************************/ -package mongo - -import ( - "github.com/edgexfoundry/edgex-go/internal/pkg/db" - "github.com/edgexfoundry/edgex-go/internal/pkg/db/mongo/models" - contract "github.com/edgexfoundry/go-mod-core-contracts/models" - "github.com/globalsign/mgo/bson" -) - -// ******************************* INTERVALS ********************************** - -// Return all the Interval(s) -// UnexpectedError - failed to retrieve intervals from the database -// Sort the events in descending order by ID - -func (mc MongoClient) Intervals() ([]contract.Interval, error) { - return mapIntervals(mc.getIntervals(bson.M{})) -} - -// Return Interval(s) up to the max number specified -// UnexpectedError - failed to retrieve intervals from the database -// Sort the intervals in descending order by ID -func (mc MongoClient) IntervalsWithLimit(limit int) ([]contract.Interval, error) { - return mapIntervals(mc.getIntervalsLimit(bson.M{}, limit)) -} - -// Return an Interval by name -// UnexpectedError - failed to retrieve interval from the database -func (mc MongoClient) IntervalByName(name string) (contract.Interval, error) { - s := mc.getSessionCopy() - defer s.Close() - - query := bson.M{"name": name} - - mi := models.Interval{} - if err := s.DB(mc.database.Name).C(db.Interval).Find(query).One(&mi); err != nil { - return contract.Interval{}, errorMap(err) - } - return mi.ToContract(), nil -} - -// Return an Interval by ID -// UnexpectedError - failed to retrieve interval from the database -func (mc MongoClient) IntervalById(id string) (contract.Interval, error) { - s := mc.getSessionCopy() - defer s.Close() - - query, err := idToBsonM(id) - if err != nil { - return contract.Interval{}, err - } - - var interval models.Interval - if err := s.DB(mc.database.Name).C(db.Interval).Find(query).One(&interval); err != nil { - return contract.Interval{}, errorMap(err) - } - return interval.ToContract(), nil -} - -// Add an Interval -// UnexpectedError - failed to add interval into the database -func (mc MongoClient) AddInterval(interval contract.Interval) (string, error) { - s := mc.getSessionCopy() - defer s.Close() - - var mapped models.Interval - id, err := mapped.FromContract(interval) - if err != nil { - return "", err - } - - // See if the name is unique and add the value descriptors - found, err := s.DB(mc.database.Name).C(db.Interval).Find(bson.M{"name": mapped.Name}).Count() - // Duplicate name - if found > 0 { - return "", db.ErrNotUnique - } - - mapped.TimestampForAdd() - - if err = s.DB(mc.database.Name).C(db.Interval).Insert(mapped); err != nil { - return "", errorMap(err) - } - - return id, nil -} - -// Update an Interval -// UnexpectedError - failed to update interval in the database -func (mc MongoClient) UpdateInterval(interval contract.Interval) error { - var mapped models.Interval - id, err := mapped.FromContract(interval) - if err != nil { - return err - } - - mapped.TimestampForUpdate() - - return mc.updateId(db.Interval, id, mapped) -} - -// Remove an Interval by ID -// UnexpectedError - failed to remove interval from the database -func (mc MongoClient) DeleteIntervalById(id string) error { - return mc.deleteById(db.Interval, id) -} - -// ******************************* INTERVAL ACTIONS ********************************** - -// Return all the Interval Action(s) -// UnexpectedError - failed to retrieve interval actions from the database -// Sort the interval actions in descending order by ID -func (mc MongoClient) IntervalActions() ([]contract.IntervalAction, error) { - return mapIntervalActions(mc.getIntervalActions(bson.M{})) -} - -// Return Interval Action(s) up to the max number specified -// UnexpectedError - failed to retrieve interval actions from the database -// Sort the interval actions in descending order by ID -func (mc MongoClient) IntervalActionsWithLimit(limit int) ([]contract.IntervalAction, error) { - return mapIntervalActions(mc.getIntervalActionsLimit(bson.M{}, limit)) -} - -// Return Interval Action(s) by interval name -// UnexpectedError - failed to retrieve interval actions from the database -// Sort the interval actions in descending order by ID -func (mc MongoClient) IntervalActionsByIntervalName(name string) ([]contract.IntervalAction, error) { - return mapIntervalActions(mc.getIntervalActions(bson.M{"interval": name})) -} - -// Return Interval Action(s) by target name -// UnexpectedError - failed to retrieve interval actions from the database -// Sort the interval actions in descending order by ID -func (mc MongoClient) IntervalActionsByTarget(name string) ([]contract.IntervalAction, error) { - return mapIntervalActions(mc.getIntervalActions(bson.M{"target": name})) -} - -// Return an Interval Action by ID -// UnexpectedError - failed to retrieve interval actions from the database -// Sort the interval actions in descending order by ID -func (mc MongoClient) IntervalActionById(id string) (contract.IntervalAction, error) { - s := mc.getSessionCopy() - defer s.Close() - - query, err := idToBsonM(id) - if err != nil { - return contract.IntervalAction{}, err - } - - var action models.IntervalAction - if err := s.DB(mc.database.Name).C(db.IntervalAction).Find(query).One(&action); err != nil { - return contract.IntervalAction{}, errorMap(err) - } - return action.ToContract(), nil -} - -// Return an Interval Action by name -// UnexpectedError - failed to retrieve interval actions from the database -// Sort the interval actions in descending order by ID -func (mc MongoClient) IntervalActionByName(name string) (contract.IntervalAction, error) { - s := mc.getSessionCopy() - defer s.Close() - - query := bson.M{"name": name} - - mia := models.IntervalAction{} - if err := s.DB(mc.database.Name).C(db.IntervalAction).Find(query).One(&mia); err != nil { - return contract.IntervalAction{}, errorMap(err) - } - return mia.ToContract(), nil -} - -// Add a new Interval Action -// UnexpectedError - failed to add interval action into the database -func (mc MongoClient) AddIntervalAction(action contract.IntervalAction) (string, error) { - s := mc.getSessionCopy() - defer s.Close() - - var mapped models.IntervalAction - id, err := mapped.FromContract(action) - if err != nil { - return "", err - } - - // See if the name is unique and add the value descriptors - found, err := s.DB(mc.database.Name).C(db.IntervalAction).Find(bson.M{"name": mapped.Name}).Count() - // Duplicate name - if found > 0 { - return "", db.ErrNotUnique - } - - mapped.TimestampForAdd() - - if err = s.DB(mc.database.Name).C(db.IntervalAction).Insert(mapped); err != nil { - return "", errorMap(err) - } - return id, nil -} - -// Update an Interval Action -// UnexpectedError - failed to update interval action in the database -func (mc MongoClient) UpdateIntervalAction(action contract.IntervalAction) error { - var mapped models.IntervalAction - id, err := mapped.FromContract(action) - if err != nil { - return err - } - - mapped.TimestampForUpdate() - - return mc.updateId(db.IntervalAction, id, mapped) -} - -// Remove an Interval Action by ID -// UnexpectedError - failed to remove interval action from the database -func (mc MongoClient) DeleteIntervalActionById(id string) error { - return mc.deleteById(db.IntervalAction, id) -} - -// ******************************* HELPER FUNCTIONS ********************************** - -// Get Interval Action(s) -func (mc MongoClient) getIntervalActions(q bson.M) ([]models.IntervalAction, error) { - s := mc.getSessionCopy() - defer s.Close() - - var mia []models.IntervalAction - if err := s.DB(mc.database.Name).C(db.IntervalAction).Find(q).All(&mia); err != nil { - return []models.IntervalAction{}, errorMap(err) - } - return mia, nil -} - -// Get Interval Action(s) with a limit -func (mc MongoClient) getIntervalActionsLimit(q bson.M, limit int) ([]models.IntervalAction, error) { - s := mc.getSessionCopy() - defer s.Close() - - // Check if limit is 0 - if limit == 0 { - return []models.IntervalAction{}, nil - } - - var mia []models.IntervalAction - if err := s.DB(mc.database.Name).C(db.IntervalAction).Find(q).Limit(limit).All(&mia); err != nil { - return []models.IntervalAction{}, errorMap(err) - } - return mia, nil -} - -// Get all Interval(s) -func (mc MongoClient) getIntervals(q bson.M) ([]models.Interval, error) { - s := mc.getSessionCopy() - defer s.Close() - - var mi []models.Interval - if err := s.DB(mc.database.Name).C(db.Interval).Find(q).All(&mi); err != nil { - return []models.Interval{}, errorMap(err) - } - return mi, nil -} - -// Get Interval(s) with a limit -func (mc MongoClient) getIntervalsLimit(q bson.M, limit int) ([]models.Interval, error) { - s := mc.getSessionCopy() - defer s.Close() - - // Check if limit is 0 - if limit == 0 { - return []models.Interval{}, nil - } - - var mi []models.Interval - if err := s.DB(mc.database.Name).C(db.Interval).Find(q).Limit(limit).All(&mi); err != nil { - return []models.Interval{}, errorMap(err) - } - return mi, nil -} - -// Map IntervalActions -func mapIntervalActions(actions []models.IntervalAction, err error) ([]contract.IntervalAction, error) { - if err != nil { - return []contract.IntervalAction{}, err - } - mapped := make([]contract.IntervalAction, 0) - for _, action := range actions { - mapped = append(mapped, action.ToContract()) - } - return mapped, nil -} - -// Map Intervals -func mapIntervals(intervals []models.Interval, err error) ([]contract.Interval, error) { - if err != nil { - return []contract.Interval{}, err - } - mapped := make([]contract.Interval, 0) - for _, interval := range intervals { - mapped = append(mapped, interval.ToContract()) - } - return mapped, nil -} - -// ******************************* UTILITY FUNCTIONS ********************************** - -// Removes all of the Interval Action(s) -// Returns number of Interval Action(s) removed -// UnexpectedError - failed to remove all of the Interval and IntervalActions from the database -func (mc MongoClient) ScrubAllIntervalActions() (int, error) { - s := mc.session.Copy() - defer s.Close() - - count, err := s.DB(mc.database.Name).C(db.IntervalAction).Count() - if err != nil { - return 0, errorMap(err) - } - _, err = s.DB(mc.database.Name).C(db.IntervalAction).RemoveAll(nil) - if err != nil { - return 0, errorMap(err) - } - - return count, nil -} - -// Removes all of the Intervals -// Removes any IntervalAction(s) previously not removed as well -// Returns number Interval(s) removed -// UnexpectedError - failed to remove all of the Interval and IntervalActions from the database -func (mc MongoClient) ScrubAllIntervals() (int, error) { - s := mc.session.Copy() - defer s.Close() - - // Ensure we have removed interval actions first - count, err := s.DB(mc.database.Name).C(db.IntervalAction).Count() - if count > 0 { - _, err = s.DB(mc.database.Name).C(db.IntervalAction).RemoveAll(nil) - if err != nil { - return 0, errorMap(err) - } - } - // count the number interval(s) were removing "overwrite interval actions count" - count, err = s.DB(mc.database.Name).C(db.Interval).Count() - if err != nil { - return 0, errorMap(err) - } - _, err = s.DB(mc.database.Name).C(db.Interval).RemoveAll(nil) - if err != nil { - return 0, errorMap(err) - } - - return count, nil -} diff --git a/internal/pkg/db/redis/CONFIGURATION.md b/internal/pkg/db/redis/CONFIGURATION.md index 0b50d44f7b..bf7a3d18ff 100644 --- a/internal/pkg/db/redis/CONFIGURATION.md +++ b/internal/pkg/db/redis/CONFIGURATION.md @@ -1,9 +1,6 @@ # Configuring Microservices to use Redis -As of EdgeX 1.0 (Edinburgh), all the microservices with the exception of logging are enabled for -Redis. At this time there is no plan to add support for logging. When deploying EdgeX via Snap, the default behavior may still be Mongo (its moving to Redis). Please refer to [EdgeX snap](https://github.com/edgexfoundry/edgex-go/blob/master/snap/README.md) for more information. - -When deploying EdgeX via Docker (or native), the default behavior is to use Mongo and you'll need to explicitly configure Redis. +As of EdgeX 2.0 (Ireland), all the microservices use Redis, which is the only supported database. ## Requirements diff --git a/internal/security/secretstore/init.go b/internal/security/secretstore/init.go index 88293e7796..bc44aa8da9 100644 --- a/internal/security/secretstore/init.go +++ b/internal/security/secretstore/init.go @@ -303,9 +303,6 @@ func (b *Bootstrap) BootstrapHandler(ctx context.Context, _ *sync.WaitGroup, _ s // So edgex/%s/redisdb is for the microservices (microservices are restricted to their specific // edgex/%s), and edgex/redisdb/* is enumerated to initialize the database. // - // The Redis implementation parallels the existing Mongo code but until the update for Redis 6, - // there is only a single Redis password. - // // Redis 5.x only supports a single shared password. When Redis 6 is released, this can be updated // to a per service password. diff --git a/internal/support/notifications/enums/database.go b/internal/support/notifications/enums/database.go deleted file mode 100644 index 8516c8e40f..0000000000 --- a/internal/support/notifications/enums/database.go +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright 2018 Dell Technologies 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. - * - *******************************************************************************/ -package enums - -import ( - "errors" -) - -type DATABASE int - -const ( - INVALID DATABASE = iota - MONGODB - MYSQL -) - -const ( - invalidStr = "invalid" - mongoStr = "mongodb" - mysqlStr = "mysql" -) - -// DATABASEArr : Add in order declared in Struct for string value -var databaseArr = [...]string{invalidStr, mongoStr, mysqlStr} - -func (db DATABASE) String() string { - if db >= INVALID && db <= MYSQL { - return databaseArr[db] - } - return invalidStr -} - -// GetDatabaseType : Return enum valude of the Database Type -func GetDatabaseType(db string) (DATABASE, error) { - if mongoStr == db { - return MONGODB, nil - } else if mysqlStr == db { - return MYSQL, nil - } else { - return INVALID, errors.New("Undefined Database Type") - } -} diff --git a/internal/support/notifications/enums/database_test.go b/internal/support/notifications/enums/database_test.go deleted file mode 100644 index a7b3c3ed52..0000000000 --- a/internal/support/notifications/enums/database_test.go +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright 2018 Dell Technologies 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. - * - *******************************************************************************/ -package enums - -import "testing" - -func TestGetDatabaseType(t *testing.T) { - tests := []struct { - name string - args string - want DATABASE - wantErr bool - }{ - {"type is mongo", "mongodb", MONGODB, false}, - {"type is mysql", "mysql", MYSQL, false}, - {"type is unknown", "foo", INVALID, true}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got, err := GetDatabaseType(tt.args) - if (err != nil) != tt.wantErr { - t.Errorf("GetDatabaseType() error = %v, wantErr %v", err, tt.wantErr) - return - } - if got != tt.want { - t.Errorf("GetDatabaseType() = %v, want %v", got, tt.want) - } - }) - } -} - -func TestStringDatabaseType(t *testing.T) { - tests := []struct { - name string - db DATABASE - }{ - {"mongo", MONGODB}, - {"mysql", MYSQL}, - {"unknown", INVALID}, - {"invalid1", INVALID - 1}, - {"invalid2", MYSQL + 1}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if tt.db.String() == "" { - t.Errorf("String should not be empty") - } - }) - } -} diff --git a/internal/support/notifications/interfaces/db.go b/internal/support/notifications/interfaces/db.go index a23c1e9ae1..1c3a5c6af9 100644 --- a/internal/support/notifications/interfaces/db.go +++ b/internal/support/notifications/interfaces/db.go @@ -16,15 +16,9 @@ package interfaces import ( - "errors" contract "github.com/edgexfoundry/go-mod-core-contracts/models" ) -type DatabaseType int8 // Database type enum -const ( - MONGO DatabaseType = iota -) - type DBClient interface { CloseSession() @@ -75,22 +69,3 @@ type DBClient interface { Cleanup() error CleanupOld(age int) error } - -type DBConfiguration struct { - DbType DatabaseType - Host string - Port int - Timeout int - DatabaseName string - Username string - Password string - ReadMax int - ResendLimit int - CleanupDefaultAge int -} - -var ErrNotFound error = errors.New("Item not found") -var ErrUnsupportedDatabase error = errors.New("Unsuppored database type") -var ErrInvalidObjectId error = errors.New("Invalid object ID") -var ErrNotUnique error = errors.New("Resource already exists") -var ErrSlugEmpty error = errors.New("Slug is nil or empty")