| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355 |
- package grpcserver
- import (
- "context"
- "errors"
- "fmt"
- "net"
- "os"
- "sync"
- "sync/atomic"
- "time"
- "log/slog"
- "google.golang.org/grpc"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/connectivity"
- "google.golang.org/grpc/credentials/insecure"
- "google.golang.org/grpc/health"
- healthpb "google.golang.org/grpc/health/grpc_health_v1"
- "google.golang.org/grpc/reflection"
- "google.golang.org/grpc/status"
- "hth/internal/config"
- hthv1 "hth/internal/gen/hth/api/v1"
- )
- type API interface {
- ListDevices(ctx context.Context) (*hthv1.ListDevicesResponse, error)
- Capabilities(ctx context.Context, id string) (*hthv1.Capabilities, error)
- Snapshot(ctx context.Context, id string) (*hthv1.Snapshot, error)
- SubscribeTelemetry(ctx context.Context, id string, resume uint64, emit func(*hthv1.Snapshot) error) error
- SubscribeEvents(ctx context.Context, id string, resume uint64, emit func(*hthv1.Event) error) error
- Faults(ctx context.Context, id string, includeInactive bool) (*hthv1.GetFaultsResponse, error)
- WatchHealth(ctx context.Context, emit func(*hthv1.HealthStatus) error) error
- StepReplay(ctx context.Context, id string) (*hthv1.StepReplayResponse, error)
- StepReplayObserve(ctx context.Context, id string) (*hthv1.StepReplayResponse, error)
- AcquireLease(ctx context.Context, req *hthv1.AcquireControlLeaseRequest) (*hthv1.ControlLease, error)
- RenewLease(ctx context.Context, req *hthv1.RenewControlLeaseRequest) (*hthv1.ControlLease, error)
- ReleaseLease(ctx context.Context, req *hthv1.ReleaseControlLeaseRequest) error
- ValidateAction(ctx context.Context, batch *hthv1.ActionBatch) (*hthv1.ActionResult, error)
- ApplyAction(ctx context.Context, batch *hthv1.ActionBatch) (*hthv1.ActionResult, error)
- EnterSafeMode(ctx context.Context, req *hthv1.EnterSafeModeRequest) (*hthv1.ActionResult, error)
- ResumeFromSafe(ctx context.Context, req *hthv1.ResumeFromSafeRequest) (*hthv1.ActionResult, error)
- SetThermalTarget(ctx context.Context, req *hthv1.SetThermalTargetRequest) (*hthv1.ThermalCommandResult, error)
- StopThermal(ctx context.Context, req *hthv1.StopThermalRequest) (*hthv1.ThermalCommandResult, error)
- GetThermalSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error)
- CaptureThermalSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error)
- RunThermalStimulus(ctx context.Context, req *hthv1.RunThermalStimulusRequest) (*hthv1.ThermalCommandResult, error)
- }
- type Servers struct {
- Observe *grpc.Server
- Control *grpc.Server
- obsL net.Listener
- ctlL net.Listener
- healthO *health.Server
- healthC *health.Server
- once sync.Once
- ErrC chan error
- obsOK atomic.Bool
- ctlOK atomic.Bool
- }
- type observeSrv struct {
- hthv1.UnimplementedObserveServiceServer
- api API
- }
- type controlSrv struct {
- hthv1.UnimplementedControlServiceServer
- api API
- }
- type thermalObserveSrv struct {
- hthv1.UnimplementedThermalObserveServiceServer
- api API
- }
- type thermalControlSrv struct {
- hthv1.UnimplementedThermalControlServiceServer
- api API
- }
- const (
- ObserveHealthService = "hth.api.v1.ObserveService"
- ControlHealthService = "hth.api.v1.ControlService"
- )
- func setHealth(h *health.Server, service string, st healthpb.HealthCheckResponse_ServingStatus) {
- if h == nil {
- return
- }
- h.SetServingStatus("", st)
- if service != "" {
- h.SetServingStatus(service, st)
- }
- }
- func Start(cfg *config.Config, api API) (*Servers, error) {
- if err := prepareSockets(cfg); err != nil {
- return nil, err
- }
- ol, err := net.Listen("unix", cfg.Sockets.Observe)
- if err != nil {
- return nil, fmt.Errorf("observe listen: %w", err)
- }
- cl, err := net.Listen("unix", cfg.Sockets.Control)
- if err != nil {
- ol.Close()
- return nil, fmt.Errorf("control listen: %w", err)
- }
- ol = wrapPeerLog(ol, "observe")
- cl = wrapPeerLog(cl, "control")
- if err := os.Chmod(cfg.Sockets.Observe, cfg.ObserveMode()); err != nil {
- ol.Close()
- cl.Close()
- return nil, err
- }
- if err := os.Chmod(cfg.Sockets.Control, cfg.ControlMode()); err != nil {
- ol.Close()
- cl.Close()
- return nil, err
- }
- if err := chownSocket(cfg.Sockets.Observe, cfg.Sockets.ObserveGroup); err != nil {
- ol.Close()
- cl.Close()
- return nil, fmt.Errorf("observe chown: %w", err)
- }
- if err := chownSocket(cfg.Sockets.Control, cfg.Sockets.ControlGroup); err != nil {
- ol.Close()
- cl.Close()
- return nil, fmt.Errorf("control chown: %w", err)
- }
- log := slog.Default()
- opts := []grpc.ServerOption{
- grpc.MaxRecvMsgSize(4 << 20),
- grpc.MaxSendMsgSize(4 << 20),
- grpc.ChainUnaryInterceptor(unaryPanicRecovery(log), peerCredUnaryInterceptor()),
- grpc.ChainStreamInterceptor(streamPanicRecovery(log), peerCredStreamInterceptor()),
- }
- obs := grpc.NewServer(opts...)
- ctl := grpc.NewServer(opts...)
- hthv1.RegisterObserveServiceServer(obs, &observeSrv{api: api})
- hthv1.RegisterControlServiceServer(ctl, &controlSrv{api: api})
- hthv1.RegisterThermalObserveServiceServer(obs, &thermalObserveSrv{api: api})
- hthv1.RegisterThermalControlServiceServer(ctl, &thermalControlSrv{api: api})
- ho := health.NewServer()
- hc := health.NewServer()
- setHealth(ho, ObserveHealthService, healthpb.HealthCheckResponse_SERVING)
- setHealth(hc, ControlHealthService, healthpb.HealthCheckResponse_SERVING)
- healthpb.RegisterHealthServer(obs, ho)
- healthpb.RegisterHealthServer(ctl, hc)
- if cfg.GRPC.Reflection {
- reflection.Register(obs)
- reflection.Register(ctl)
- }
- s := &Servers{Observe: obs, Control: ctl, obsL: ol, ctlL: cl, healthO: ho, healthC: hc, ErrC: make(chan error, 2)}
- s.obsOK.Store(true)
- s.ctlOK.Store(true)
- go func() {
- err := obs.Serve(ol)
- s.obsOK.Store(false)
- if err != nil && !errors.Is(err, grpc.ErrServerStopped) {
- setHealth(ho, ObserveHealthService, healthpb.HealthCheckResponse_NOT_SERVING)
- select {
- case s.ErrC <- fmt.Errorf("observe grpc Serve: %w", err):
- default:
- }
- }
- }()
- go func() {
- err := ctl.Serve(cl)
- s.ctlOK.Store(false)
- if err != nil && !errors.Is(err, grpc.ErrServerStopped) {
- setHealth(hc, ControlHealthService, healthpb.HealthCheckResponse_NOT_SERVING)
- select {
- case s.ErrC <- fmt.Errorf("control grpc Serve: %w", err):
- default:
- }
- }
- }()
- return s, nil
- }
- func (s *Servers) ObserveAlive() bool {
- return s != nil && s.obsOK.Load()
- }
- func (s *Servers) ControlAlive() bool {
- return s != nil && s.ctlOK.Load()
- }
- func (s *Servers) Stop() {
- if s == nil {
- return
- }
- s.once.Do(func() {
- if s.healthO != nil {
- setHealth(s.healthO, ObserveHealthService, healthpb.HealthCheckResponse_NOT_SERVING)
- }
- if s.healthC != nil {
- setHealth(s.healthC, ControlHealthService, healthpb.HealthCheckResponse_NOT_SERVING)
- }
- done := make(chan struct{})
- go func() {
- if s.Observe != nil {
- s.Observe.GracefulStop()
- }
- if s.Control != nil {
- s.Control.GracefulStop()
- }
- close(done)
- }()
- select {
- case <-done:
- case <-time.After(2 * time.Second):
- if s.Observe != nil {
- s.Observe.Stop()
- }
- if s.Control != nil {
- s.Control.Stop()
- }
- }
- })
- }
- func (o *observeSrv) ListDevices(ctx context.Context, _ *hthv1.ListDevicesRequest) (*hthv1.ListDevicesResponse, error) {
- return o.api.ListDevices(ctx)
- }
- func (o *observeSrv) GetCapabilities(ctx context.Context, req *hthv1.GetCapabilitiesRequest) (*hthv1.GetCapabilitiesResponse, error) {
- c, err := o.api.Capabilities(ctx, req.DeviceId)
- if err != nil {
- return nil, err
- }
- return &hthv1.GetCapabilitiesResponse{Capabilities: c}, nil
- }
- func (o *observeSrv) GetSnapshot(ctx context.Context, req *hthv1.GetSnapshotRequest) (*hthv1.GetSnapshotResponse, error) {
- s, err := o.api.Snapshot(ctx, req.DeviceId)
- if err != nil {
- return nil, err
- }
- return &hthv1.GetSnapshotResponse{Snapshot: s}, nil
- }
- func (o *observeSrv) SubscribeTelemetry(req *hthv1.SubscribeTelemetryRequest, stream hthv1.ObserveService_SubscribeTelemetryServer) error {
- return o.api.SubscribeTelemetry(stream.Context(), req.DeviceId, req.ResumeAfterEventId, stream.Send)
- }
- func (o *observeSrv) SubscribeEvents(req *hthv1.SubscribeEventsRequest, stream hthv1.ObserveService_SubscribeEventsServer) error {
- return o.api.SubscribeEvents(stream.Context(), req.DeviceId, req.ResumeAfterEventId, stream.Send)
- }
- func (o *observeSrv) GetFaults(ctx context.Context, req *hthv1.GetFaultsRequest) (*hthv1.GetFaultsResponse, error) {
- return o.api.Faults(ctx, req.DeviceId, req.IncludeInactive)
- }
- func (o *observeSrv) WatchHealth(_ *hthv1.WatchHealthRequest, stream hthv1.ObserveService_WatchHealthServer) error {
- return o.api.WatchHealth(stream.Context(), stream.Send)
- }
- func (o *observeSrv) StepReplay(ctx context.Context, req *hthv1.StepReplayRequest) (*hthv1.StepReplayResponse, error) {
- return o.api.StepReplayObserve(ctx, req.GetDeviceId())
- }
- func (c *controlSrv) StepReplay(ctx context.Context, req *hthv1.StepReplayRequest) (*hthv1.StepReplayResponse, error) {
- return c.api.StepReplay(ctx, req.GetDeviceId())
- }
- func (c *controlSrv) AcquireControlLease(ctx context.Context, req *hthv1.AcquireControlLeaseRequest) (*hthv1.LeaseResponse, error) {
- l, err := c.api.AcquireLease(ctx, req)
- if err != nil {
- return nil, status.Error(codes.FailedPrecondition, err.Error())
- }
- return &hthv1.LeaseResponse{Lease: l}, nil
- }
- func (c *controlSrv) RenewControlLease(ctx context.Context, req *hthv1.RenewControlLeaseRequest) (*hthv1.LeaseResponse, error) {
- l, err := c.api.RenewLease(ctx, req)
- if err != nil {
- return nil, status.Error(codes.FailedPrecondition, err.Error())
- }
- return &hthv1.LeaseResponse{Lease: l}, nil
- }
- func (c *controlSrv) ReleaseControlLease(ctx context.Context, req *hthv1.ReleaseControlLeaseRequest) (*hthv1.LeaseResponse, error) {
- if err := c.api.ReleaseLease(ctx, req); err != nil {
- return nil, status.Error(codes.FailedPrecondition, err.Error())
- }
- return &hthv1.LeaseResponse{}, nil
- }
- func (c *controlSrv) ValidateAction(ctx context.Context, req *hthv1.ValidateActionRequest) (*hthv1.ActionResult, error) {
- return c.api.ValidateAction(ctx, req.Batch)
- }
- func (c *controlSrv) ApplyAction(ctx context.Context, req *hthv1.ApplyActionRequest) (*hthv1.ActionResult, error) {
- return c.api.ApplyAction(ctx, req.Batch)
- }
- func (c *controlSrv) EnterSafeMode(ctx context.Context, req *hthv1.EnterSafeModeRequest) (*hthv1.ActionResult, error) {
- return c.api.EnterSafeMode(ctx, req)
- }
- func (c *controlSrv) ResumeFromSafe(ctx context.Context, req *hthv1.ResumeFromSafeRequest) (*hthv1.ActionResult, error) {
- return c.api.ResumeFromSafe(ctx, req)
- }
- func (o *thermalObserveSrv) GetSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error) {
- return o.api.GetThermalSnapshot(ctx, req)
- }
- func (o *thermalObserveSrv) CaptureSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error) {
- return o.api.CaptureThermalSnapshot(ctx, req)
- }
- func (c *thermalControlSrv) SetTarget(ctx context.Context, req *hthv1.SetThermalTargetRequest) (*hthv1.ThermalCommandResult, error) {
- return c.api.SetThermalTarget(ctx, req)
- }
- func (c *thermalControlSrv) Stop(ctx context.Context, req *hthv1.StopThermalRequest) (*hthv1.ThermalCommandResult, error) {
- return c.api.StopThermal(ctx, req)
- }
- func (c *thermalControlSrv) RunStimulus(ctx context.Context, req *hthv1.RunThermalStimulusRequest) (*hthv1.ThermalCommandResult, error) {
- return c.api.RunThermalStimulus(ctx, req)
- }
- func DialUnix(path string, timeout time.Duration) (*grpc.ClientConn, error) {
- conn, err := grpc.NewClient("unix://"+path,
- grpc.WithTransportCredentials(insecure.NewCredentials()),
- grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(4<<20)),
- )
- if err != nil {
- return nil, err
- }
- ctx, cancel := context.WithTimeout(context.Background(), timeout)
- defer cancel()
- conn.Connect()
- for {
- st := conn.GetState()
- if st == connectivity.Ready {
- return conn, nil
- }
- if st == connectivity.Shutdown {
- _ = conn.Close()
- return nil, fmt.Errorf("grpc unix %s shutdown", path)
- }
- if !conn.WaitForStateChange(ctx, st) {
- _ = conn.Close()
- return nil, ctx.Err()
- }
- }
- }
|