Skip to content
Snippets Groups Projects
deviceStore.go 6.97 KiB
Newer Older
  • Learn to ignore specific revisions
  • package nucleus
    
    import (
    	"fmt"
    
    	spb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/southbound"
    	tpb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/transport"
    	"code.fbi.h-da.de/danet/gosdn/controller/interfaces/device"
    	"code.fbi.h-da.de/danet/gosdn/controller/interfaces/southbound"
    	"code.fbi.h-da.de/danet/gosdn/controller/nucleus/database"
    	"code.fbi.h-da.de/danet/gosdn/controller/nucleus/errors"
    	"code.fbi.h-da.de/danet/gosdn/controller/store"
    	"go.mongodb.org/mongo-driver/bson"
    	"go.mongodb.org/mongo-driver/bson/primitive"
    	"go.mongodb.org/mongo-driver/mongo/options"
    
    	"github.com/google/uuid"
    	log "github.com/sirupsen/logrus"
    )
    
    const (
    	deviceStoreName = "device"
    )
    
    // DeviceStore is used to store Devices
    type DeviceStore struct {
    	storeName string
    	sbiStore  southbound.SbiStore
    }
    
    // LoadedDevice represents a Orchestrated Networking Device that was loaeded
    // by using the Load() method of the DeviceStore.
    type LoadedDevice struct {
    	// DeviceID represents the UUID of the LoadedDevice.
    	DeviceID string `json:"id" bson:"_id,omitempty"`
    	// Name represents the name of the LoadedDevice.
    	Name string `json:"name,omitempty"`
    	// TransportType represent the type of the transport in use of the LoadedDevice.
    	TransportType string `json:"transport_type,omitempty"`
    	// TransportAddress represents the address from which the device can be reached via the transport method.
    	TransportAddress string `json:"transport_address,omitempty"`
    	// TransportUsername is used for authentication via the transport method in use.
    	TransportUsername string `json:"transport_username,omitempty"`
    	// TransportPassword is used for authentication via the transport method in use.
    	TransportPassword   string `json:"transport_password,omitempty"`
    	TransportOptionCsbi bool   `json:"transport_option_csbi,omitempty"`
    	// SBI indicates the southbound interface, which is used by this device as UUID.
    	SBI string `json:"sbi,omitempty"`
    }
    
    // ID returns the ID of the LoadedDevice as UUID.
    func (ld LoadedDevice) ID() uuid.UUID {
    	return uuid.MustParse(ld.DeviceID)
    }
    
    // NewDeviceStore returns a DeviceStore
    func NewDeviceStore(pndUUID uuid.UUID, sbiStore southbound.SbiStore) device.Store {
    	storeMode := store.GetStoreMode()
    	log.Debugf("StoreMode: %s", storeMode)
    
    	switch storeMode {
    	case store.Filesystem:
    		store := NewGenericStore[device.Device]()
    
    		return &store
    	case store.Database:
    		return &DeviceStore{
    			storeName: fmt.Sprintf("device-store-%s.json", pndUUID.String()),
    			sbiStore:  sbiStore,
    		}
    	case store.Memory:
    		store := NewGenericStore[device.Device]()
    
    		return &store
    	default:
    		return nil
    	}
    }
    
    // Get takes a Device's UUID or name and returns the Device.
    func (s *DeviceStore) Get(query store.Query) (device.Device, error) {
    	var loadedDevice LoadedDevice
    
    	client, ctx, cancel := database.GetMongoConnection()
    	defer cancel()
    	defer client.Disconnect(ctx)
    
    	db := client.Database(database.DatabaseName)
    	collection := db.Collection(s.storeName)
    	result := collection.FindOne(ctx, bson.D{primitive.E{Key: "_id", Value: query.ID}})
    	if result == nil {
    		return nil, errors.ErrCouldNotFind{StoreName: pndStoreName}
    	}
    
    	err := result.Decode(&loadedDevice)
    	if err != nil {
    		db := client.Database(database.DatabaseName)
    		collection := db.Collection(s.storeName)
    		result := collection.FindOne(ctx, bson.D{primitive.E{Key: "_id", Value: query.Name}})
    		if result == nil {
    			return nil, errors.ErrCouldNotFind{StoreName: pndStoreName}
    		}
    
    		err := result.Decode(&loadedDevice)
    		if err != nil {
    			log.Printf("Failed marshalling %v", err)
    			return nil, errors.ErrCouldNotFind{StoreName: pndStoreName}
    		}
    	}
    
    	sbiForDevice, err := s.sbiStore.Get(store.Query{ID: uuid.MustParse(loadedDevice.SBI)})
    	if err != nil {
    		return nil, err
    	}
    
    	d, err := NewDevice(
    		loadedDevice.Name,
    		uuid.MustParse(loadedDevice.DeviceID),
    		&tpb.TransportOption{
    			Address:  loadedDevice.TransportAddress,
    			Username: loadedDevice.TransportUsername,
    			Password: loadedDevice.TransportPassword,
    			TransportOption: &tpb.TransportOption_GnmiTransportOption{
    				GnmiTransportOption: &tpb.GnmiTransportOption{},
    			},
    			Type: spb.Type_TYPE_OPENCONFIG,
    		}, sbiForDevice)
    
    	if err != nil {
    		return nil, err
    	}
    
    	return d, nil
    }
    
    // GetAll returns all stored devices.
    func (s *DeviceStore) GetAll() ([]device.Device, error) {
    	var loadedDevices []LoadedDevice
    	var devices []device.Device
    
    	client, ctx, cancel := database.GetMongoConnection()
    	defer cancel()
    	defer client.Disconnect(ctx)
    	db := client.Database(database.DatabaseName)
    	collection := db.Collection(s.storeName)
    
    	cursor, err := collection.Find(ctx, bson.D{})
    	if err != nil {
    		return nil, err
    	}
    	defer cursor.Close(ctx)
    
    	err = cursor.All(ctx, &loadedDevices)
    	if err != nil {
    		log.Printf("Failed marshalling %v", err)
    
    		return nil, errors.ErrCouldNotMarshall{StoreName: pndStoreName}
    	}
    
    	for _, device := range loadedDevices {
    		sbiForDevice, err := s.sbiStore.Get(store.Query{ID: uuid.MustParse(device.SBI)})
    		d, err := NewDevice(
    			device.Name,
    			uuid.MustParse(device.DeviceID),
    			&tpb.TransportOption{
    				Address:  device.TransportAddress,
    				Username: device.TransportUsername,
    				Password: device.TransportPassword,
    				TransportOption: &tpb.TransportOption_GnmiTransportOption{
    					GnmiTransportOption: &tpb.GnmiTransportOption{},
    				},
    				Type: spb.Type_TYPE_OPENCONFIG,
    			}, sbiForDevice)
    		if err != nil {
    			return nil, err
    		}
    
    		devices = append(devices, d)
    	}
    
    	return devices, nil
    }
    
    // Add adds a device to the device store.
    func (s *DeviceStore) Add(deviceToAdd device.Device) error {
    	client, ctx, cancel := database.GetMongoConnection()
    	defer cancel()
    	defer client.Disconnect(ctx)
    
    	_, err := client.Database(database.DatabaseName).
    		Collection(s.storeName).
    		InsertOne(ctx, deviceToAdd)
    	if err != nil {
    		log.Printf("Could not create Device: %v", err)
    		return errors.ErrCouldNotCreate{StoreName: pndStoreName}
    	}
    
    	return nil
    }
    
    // Update updates a existing device.
    func (s *DeviceStore) Update(deviceToUpdate device.Device) error {
    	var updatedDevice device.Device
    
    	client, ctx, cancel := database.GetMongoConnection()
    	defer cancel()
    	defer client.Disconnect(ctx)
    
    	update := bson.M{
    		"$set": deviceToUpdate,
    	}
    
    	upsert := false
    	after := options.After
    	opt := options.FindOneAndUpdateOptions{
    		Upsert:         &upsert,
    		ReturnDocument: &after,
    	}
    
    	err := client.Database(database.DatabaseName).
    		Collection(s.storeName).
    		FindOneAndUpdate(
    			ctx, bson.M{"id": deviceToUpdate.ID}, update, &opt).
    		Decode(&updatedDevice)
    	if err != nil {
    		log.Printf("Could not update Device: %v", err)
    
    		return errors.ErrCouldNotUpdate{StoreName: pndStoreName}
    	}
    
    	return nil
    }
    
    // Delete deletes a device from the device store.
    func (s *DeviceStore) Delete(deviceToDelete device.Device) error {
    	client, ctx, cancel := database.GetMongoConnection()
    	defer cancel()
    	defer client.Disconnect(ctx)
    
    	db := client.Database(database.DatabaseName)
    	collection := db.Collection(s.storeName)
    	_, err := collection.DeleteOne(ctx, bson.D{primitive.E{Key: deviceToDelete.ID().String()}})
    	if err != nil {
    		return err
    	}
    
    	return nil
    }