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

import (
	"code.fbi.h-da.de/cocsn/gosdn/forks/goarista/gnmi"
	"code.fbi.h-da.de/cocsn/gosdn/nucleus"
	"context"
	"fmt"
	gpb "github.com/openconfig/gnmi/proto/gnmi"
	log "github.com/sirupsen/logrus"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// Subscribe starts a gNMI subscriber requersting the specified paths on the target and
// logs the response to stdout. Only 'stream' mode with 'sample' operation supported.
func Subscribe(a, u, p string, sample, heartbeat int64, args ...string) error {
	sbi := &nucleus.OpenConfig{}
	tOpts := &nucleus.GnmiTransportOptions{
		Config: gnmi.Config{
			Addr:     a,
			Username: u,
			Password: p,
			Encoding: gpb.Encoding_JSON_IETF,
		},
		SetNode:  sbi.SetNode(),
		RespChan: make(chan *gpb.SubscribeResponse),
	}

	device, err := nucleus.NewDevice(sbi, tOpts)
	if err != nil {
		return err
	}

	opts := &gnmi.SubscribeOptions{
		UpdatesOnly:       false,
		Prefix:            "",
		Mode:              "stream",
		StreamMode:        "sample",
		SampleInterval:    uint64(sample * time.Second.Nanoseconds()),
		SuppressRedundant: false,
		HeartbeatInterval: uint64(heartbeat * time.Second.Nanoseconds()),
		Paths:             gnmi.SplitPaths(args),
		Origin:            "",
		Target:            a,
	}
	done := make(chan os.Signal, 1)
	signal.Notify(done, syscall.SIGILL, syscall.SIGTERM)
	ctx := context.WithValue(context.Background(), "opts", opts)
	go func() {
		if err := device.Transport.Subscribe(ctx); err != nil {
			log.Fatal(err)
		}
	}()
	fmt.Println("awaiting signal")
	<-done
	fmt.Println("exiting")
	return nil
}