Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
grpc.go 2.39 KiB
package api

import (
	"context"
	"errors"
	"time"

	pb "code.fbi.h-da.de/cocsn/api/go/gosdn/core"
	ppb "code.fbi.h-da.de/cocsn/api/go/gosdn/pnd"
	nbi "code.fbi.h-da.de/cocsn/gosdn/northbound/client"

	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"

	"google.golang.org/grpc"
)

var dialOptions []grpc.DialOption

func init() {
	dialOptions = []grpc.DialOption{
		grpc.WithInsecure(),
	}
}

// Init initialises the CLI client.
func Init(addr string) error {
	ctx := context.Background()
	resp, err := getAllCore(ctx, addr)
	if err != nil {
		return err
	}
	if len(resp.Pnd) > 0 {
		pid := resp.Pnd[0].Id
		viper.Set("CLI_PND", pid)
		log.Infof("PND: %v", pid)
		if len(resp.Pnd[0].Sbi) != 0 {
			sbi := resp.Pnd[0].Sbi[0].Id
			viper.Set("CLI_SBI", sbi)
			log.Infof("SBI: %v", sbi)
		}
	}
	return viper.WriteConfig()
}

// GetIds requests all UUID information from the controller
func GetIds(addr string) ([]*ppb.PrincipalNetworkDomain, error) {
	ctx := context.Background()
	resp, err := getAllCore(ctx, addr)
	if err != nil {
		return nil, err
	}
	return resp.Pnd, nil
}

func getAllCore(ctx context.Context, addr string) (*pb.GetResponse, error) {
	coreClient, err := nbi.CoreClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}
	req := &pb.GetRequest{
		Timestamp: time.Now().UnixNano(),
		All:       true,
	}
	return coreClient.Get(ctx, req)
}

// AddPnd takes a name, description and SBI UUID to create a new
// PrincipalNetworkDomain on the controller
func AddPnd(addr, name, description, sbi string) (*pb.SetResponse, error) {
	coreClient, err := nbi.CoreClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}
	ctx := context.Background()
	req := &pb.SetRequest{
		Timestamp: time.Now().UnixNano(),
		Pnd: []*pb.SetPnd{
			{
				Name:        name,
				Description: description,
				Sbi:         sbi,
			},
		},
	}

	return coreClient.Set(ctx, req)
}

// GetPnd requests one or several PrincipalNetworkDomains from the
// controller. To request all PrincipalNetworkDomains without providing
// names or UUIDs use GetIds()
func GetPnd(addr string, args ...string) (*pb.GetResponse, error) {
	coreClient, err := nbi.CoreClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}
	if len(args) <= 0 {
		return nil, errors.New("not enough arguments")
	}
	ctx := context.Background()
	req := &pb.GetRequest{
		Timestamp: time.Now().UnixNano(),
		Pid:       args,
	}
	return coreClient.Get(ctx, req)
}