Create scaffolding of ddl-simulator

Implement global server as control plane

Implement device to get their info from global server and connect each
others
This commit is contained in:
Pengzhan Hao
2024-12-17 07:31:18 +00:00
commit d6e129179c
21 changed files with 1653 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
package device
import (
"context"
"fmt"
"time"
pb "git.pengzhan.dev/ddp-simulator/proto"
"github.com/cenkalti/backoff/v4"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func (d *Device) RegisterClient() error {
conn, err := grpc.NewClient(fmt.Sprintf("%s:%d", d.ParentIP, d.ParentPort), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalf("failed to connect to global server: %v", err)
}
defer conn.Close()
client := pb.NewDeviceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
children := make([]string, 0)
for _, child := range d.Children {
children = append(children, child.ID)
}
_, err = client.Register(ctx, &pb.RegisterRequest{
Id: d.ID,
Role: d.Role,
Ip: d.IP,
Port: int32(d.Port),
ChildrenIds: children,
Capacity: d.Capacity,
})
return err
}
func (d *Device) RegisterClientRetry(ctx context.Context, timeout time.Duration) error {
b := backoff.NewExponentialBackOff()
b.InitialInterval = 1 * time.Second
b.MaxElapsedTime = timeout
retryOp := func() error {
return d.RegisterClient()
}
err := backoff.Retry(retryOp, backoff.WithContext(b, ctx))
return err
}
+60
View File
@@ -0,0 +1,60 @@
package device
import (
"context"
"time"
pb "git.pengzhan.dev/ddp-simulator/proto"
log "github.com/sirupsen/logrus"
)
type Device struct {
pb.UnimplementedDeviceServer
ID string
Role string
IP string
Port int
ParentID *string
ParentIP string
ParentPort int
Capacity *float32
Children map[string]*Device
}
func NewDevice(id, role, ip string, port int) *Device {
return &Device{
ID: id,
Role: role,
IP: ip,
Port: port,
Children: make(map[string]*Device),
}
}
func (d *Device) UpdateCapacity(capacity *float32) {
d.Capacity = capacity
}
func (d *Device) UpdateParent(parentID *string, parentIP string, parentPort int) {
d.ParentID = parentID
d.ParentIP = parentIP
d.ParentPort = parentPort
}
func (d *Device) Register(ctx context.Context, in *pb.RegisterRequest) (*pb.RegisterResponse, error) {
child := NewDevice(in.Id, in.Role, in.Ip, int(in.Port))
if in.Capacity != nil {
child.UpdateCapacity(in.Capacity)
}
d.Children[in.Id] = child
log.WithField("device", d.ID).Infof("device %s claims on device %s as its child", child.ID, d.ID)
// Update with parent
if d.ParentID != nil {
if err := d.RegisterClientRetry(ctx, 30*time.Second); err != nil {
log.WithField("device", d.ID).Fatalf("failed to register: %v", err)
}
}
return &pb.RegisterResponse{}, nil
}