Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix issue #204: Added validation to avoid duplication of mac addresses in the hardware database #205

Merged
merged 2 commits into from
Jul 9, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions grpc-server/hardware.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package grpcserver
import (
"context"
"encoding/json"
"fmt"
"time"

"github.com/pkg/errors"
Expand All @@ -14,6 +15,11 @@ import (
"google.golang.org/grpc/status"
)

const (
conflictMACAddr = "conflicting hardware MAC address %v provided with hardware data/info"
duplicateMAC = "Duplicate MAC address found"
)

func (s *server) Push(ctx context.Context, in *hardware.PushRequest) (*hardware.Empty, error) {
logger.Info("push")
labels := prometheus.Labels{"method": "Push", "op": ""}
Expand All @@ -32,9 +38,11 @@ func (s *server) Push(ctx context.Context, in *hardware.PushRequest) (*hardware.
return &hardware.Empty{}, err
}

// TODO: somewhere here validate json (if ip addr contains cidr, etc.)

logger.With("id", hw.Id).Info("data pushed")
// validate the hardware data to avoid duplicate mac address
err := s.validateHardwareData(ctx, hw)
if err != nil {
return &hardware.Empty{}, err
}

var fn func() error
msg := ""
Expand Down Expand Up @@ -67,6 +75,7 @@ func (s *server) Push(ctx context.Context, in *hardware.PushRequest) (*hardware.
}
l.Error(err)
}
logger.With("id", hw.Id).Info("data pushed")

s.watchLock.RLock()
if ch := s.watch[hw.Id]; ch != nil {
Expand Down Expand Up @@ -285,3 +294,24 @@ func (s *server) Delete(ctx context.Context, in *hardware.DeleteRequest) (*hardw

return &hardware.Empty{}, err
}

func (s *server) validateHardwareData(ctx context.Context, hw *hardware.Hardware) error {
interfaces := hw.GetNetwork().GetInterfaces()
for i := range hw.GetNetwork().GetInterfaces() {
data, _ := db.GetByMAC(ctx, s.db, interfaces[i].GetDhcp().GetMac())
if data != "" {
logger.With("MAC", interfaces[i].GetDhcp().GetMac()).Info(duplicateMAC)
newhw := hardware.Hardware{}
err := json.Unmarshal([]byte(data), &newhw)
if err != nil {
logger.Error(err, "Failed to unmarshal hardware data")
return err
}
if newhw.Id == hw.Id {
return nil
}
return errors.New(fmt.Sprintf(conflictMACAddr, interfaces[i].GetDhcp().GetMac()))
}
}
return nil
}