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:
@@ -0,0 +1,92 @@
|
||||
package global
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
pb "git.pengzhan.dev/ddp-simulator/proto"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type GlobalServer struct {
|
||||
pb.UnimplementedGlobalServiceServer
|
||||
|
||||
Configs map[string]config
|
||||
}
|
||||
|
||||
type config struct {
|
||||
ID string `json:"id"`
|
||||
Role string `json:"role"`
|
||||
Capacity float32 `json:"capacity"`
|
||||
IP string `json:"ip"`
|
||||
Port int `json:"port"`
|
||||
ParentID string `json:"parentID"`
|
||||
ParentIP string `json:"parentIP"`
|
||||
ParentPort int `json:"parentPort"`
|
||||
}
|
||||
|
||||
func NewGlobalServer(configPath string) *GlobalServer {
|
||||
configs, err := ReadConfigFromPath(configPath)
|
||||
if err != nil {
|
||||
log.Fatalf("could not read config file: %v", err)
|
||||
}
|
||||
return &GlobalServer{
|
||||
Configs: configs,
|
||||
}
|
||||
}
|
||||
|
||||
func ReadConfigFromPath(configPath string) (map[string]config, error) {
|
||||
file, err := os.Open(configPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not open file: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
fileContent, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not read file content: %v", err)
|
||||
}
|
||||
|
||||
var configs []config
|
||||
err = json.Unmarshal(fileContent, &configs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("could not parse JSON content: %v", err)
|
||||
}
|
||||
|
||||
configMap := make(map[string]config)
|
||||
|
||||
for _, c := range configs {
|
||||
configMap[c.ID] = c
|
||||
}
|
||||
|
||||
return configMap, nil
|
||||
}
|
||||
|
||||
func (g *GlobalServer) Init(ctx context.Context, in *pb.InitRequest) (*pb.InitResponse, error) {
|
||||
config, ok := g.Configs[in.Id]
|
||||
if !ok {
|
||||
log.Errorf("device %s not found", in.Id)
|
||||
return nil, fmt.Errorf("device %s not found", in.Id)
|
||||
}
|
||||
log.Infof("device %s init", config.ID)
|
||||
|
||||
resp := &pb.InitResponse{
|
||||
Role: config.Role,
|
||||
Capacity: proto.Float32(config.Capacity),
|
||||
Ip: config.IP,
|
||||
Port: int32(config.Port),
|
||||
}
|
||||
if config.ParentID != "" {
|
||||
resp.ParentId = proto.String(config.ParentID)
|
||||
resp.Pip = proto.String(config.ParentIP)
|
||||
resp.Pport = proto.Int32(int32(config.ParentPort))
|
||||
}
|
||||
if config.Capacity != 0 {
|
||||
resp.Capacity = proto.Float32(config.Capacity)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
Reference in New Issue
Block a user