server.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. package grpcserver
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "os"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. "log/slog"
  12. "google.golang.org/grpc"
  13. "google.golang.org/grpc/codes"
  14. "google.golang.org/grpc/connectivity"
  15. "google.golang.org/grpc/credentials/insecure"
  16. "google.golang.org/grpc/health"
  17. healthpb "google.golang.org/grpc/health/grpc_health_v1"
  18. "google.golang.org/grpc/reflection"
  19. "google.golang.org/grpc/status"
  20. "hth/internal/config"
  21. hthv1 "hth/internal/gen/hth/api/v1"
  22. )
  23. type API interface {
  24. ListDevices(ctx context.Context) (*hthv1.ListDevicesResponse, error)
  25. Capabilities(ctx context.Context, id string) (*hthv1.Capabilities, error)
  26. Snapshot(ctx context.Context, id string) (*hthv1.Snapshot, error)
  27. SubscribeTelemetry(ctx context.Context, id string, resume uint64, emit func(*hthv1.Snapshot) error) error
  28. SubscribeEvents(ctx context.Context, id string, resume uint64, emit func(*hthv1.Event) error) error
  29. Faults(ctx context.Context, id string, includeInactive bool) (*hthv1.GetFaultsResponse, error)
  30. WatchHealth(ctx context.Context, emit func(*hthv1.HealthStatus) error) error
  31. StepReplay(ctx context.Context, id string) (*hthv1.StepReplayResponse, error)
  32. StepReplayObserve(ctx context.Context, id string) (*hthv1.StepReplayResponse, error)
  33. AcquireLease(ctx context.Context, req *hthv1.AcquireControlLeaseRequest) (*hthv1.ControlLease, error)
  34. RenewLease(ctx context.Context, req *hthv1.RenewControlLeaseRequest) (*hthv1.ControlLease, error)
  35. ReleaseLease(ctx context.Context, req *hthv1.ReleaseControlLeaseRequest) error
  36. ValidateAction(ctx context.Context, batch *hthv1.ActionBatch) (*hthv1.ActionResult, error)
  37. ApplyAction(ctx context.Context, batch *hthv1.ActionBatch) (*hthv1.ActionResult, error)
  38. EnterSafeMode(ctx context.Context, req *hthv1.EnterSafeModeRequest) (*hthv1.ActionResult, error)
  39. ResumeFromSafe(ctx context.Context, req *hthv1.ResumeFromSafeRequest) (*hthv1.ActionResult, error)
  40. SetThermalTarget(ctx context.Context, req *hthv1.SetThermalTargetRequest) (*hthv1.ThermalCommandResult, error)
  41. StopThermal(ctx context.Context, req *hthv1.StopThermalRequest) (*hthv1.ThermalCommandResult, error)
  42. GetThermalSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error)
  43. CaptureThermalSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error)
  44. RunThermalStimulus(ctx context.Context, req *hthv1.RunThermalStimulusRequest) (*hthv1.ThermalCommandResult, error)
  45. }
  46. type Servers struct {
  47. Observe *grpc.Server
  48. Control *grpc.Server
  49. obsL net.Listener
  50. ctlL net.Listener
  51. healthO *health.Server
  52. healthC *health.Server
  53. once sync.Once
  54. ErrC chan error
  55. obsOK atomic.Bool
  56. ctlOK atomic.Bool
  57. }
  58. type observeSrv struct {
  59. hthv1.UnimplementedObserveServiceServer
  60. api API
  61. }
  62. type controlSrv struct {
  63. hthv1.UnimplementedControlServiceServer
  64. api API
  65. }
  66. type thermalObserveSrv struct {
  67. hthv1.UnimplementedThermalObserveServiceServer
  68. api API
  69. }
  70. type thermalControlSrv struct {
  71. hthv1.UnimplementedThermalControlServiceServer
  72. api API
  73. }
  74. const (
  75. ObserveHealthService = "hth.api.v1.ObserveService"
  76. ControlHealthService = "hth.api.v1.ControlService"
  77. )
  78. func setHealth(h *health.Server, service string, st healthpb.HealthCheckResponse_ServingStatus) {
  79. if h == nil {
  80. return
  81. }
  82. h.SetServingStatus("", st)
  83. if service != "" {
  84. h.SetServingStatus(service, st)
  85. }
  86. }
  87. func Start(cfg *config.Config, api API) (*Servers, error) {
  88. if err := prepareSockets(cfg); err != nil {
  89. return nil, err
  90. }
  91. ol, err := net.Listen("unix", cfg.Sockets.Observe)
  92. if err != nil {
  93. return nil, fmt.Errorf("observe listen: %w", err)
  94. }
  95. cl, err := net.Listen("unix", cfg.Sockets.Control)
  96. if err != nil {
  97. ol.Close()
  98. return nil, fmt.Errorf("control listen: %w", err)
  99. }
  100. ol = wrapPeerLog(ol, "observe")
  101. cl = wrapPeerLog(cl, "control")
  102. if err := os.Chmod(cfg.Sockets.Observe, cfg.ObserveMode()); err != nil {
  103. ol.Close()
  104. cl.Close()
  105. return nil, err
  106. }
  107. if err := os.Chmod(cfg.Sockets.Control, cfg.ControlMode()); err != nil {
  108. ol.Close()
  109. cl.Close()
  110. return nil, err
  111. }
  112. if err := chownSocket(cfg.Sockets.Observe, cfg.Sockets.ObserveGroup); err != nil {
  113. ol.Close()
  114. cl.Close()
  115. return nil, fmt.Errorf("observe chown: %w", err)
  116. }
  117. if err := chownSocket(cfg.Sockets.Control, cfg.Sockets.ControlGroup); err != nil {
  118. ol.Close()
  119. cl.Close()
  120. return nil, fmt.Errorf("control chown: %w", err)
  121. }
  122. log := slog.Default()
  123. opts := []grpc.ServerOption{
  124. grpc.MaxRecvMsgSize(4 << 20),
  125. grpc.MaxSendMsgSize(4 << 20),
  126. grpc.ChainUnaryInterceptor(unaryPanicRecovery(log), peerCredUnaryInterceptor()),
  127. grpc.ChainStreamInterceptor(streamPanicRecovery(log), peerCredStreamInterceptor()),
  128. }
  129. obs := grpc.NewServer(opts...)
  130. ctl := grpc.NewServer(opts...)
  131. hthv1.RegisterObserveServiceServer(obs, &observeSrv{api: api})
  132. hthv1.RegisterControlServiceServer(ctl, &controlSrv{api: api})
  133. hthv1.RegisterThermalObserveServiceServer(obs, &thermalObserveSrv{api: api})
  134. hthv1.RegisterThermalControlServiceServer(ctl, &thermalControlSrv{api: api})
  135. ho := health.NewServer()
  136. hc := health.NewServer()
  137. setHealth(ho, ObserveHealthService, healthpb.HealthCheckResponse_SERVING)
  138. setHealth(hc, ControlHealthService, healthpb.HealthCheckResponse_SERVING)
  139. healthpb.RegisterHealthServer(obs, ho)
  140. healthpb.RegisterHealthServer(ctl, hc)
  141. if cfg.GRPC.Reflection {
  142. reflection.Register(obs)
  143. reflection.Register(ctl)
  144. }
  145. s := &Servers{Observe: obs, Control: ctl, obsL: ol, ctlL: cl, healthO: ho, healthC: hc, ErrC: make(chan error, 2)}
  146. s.obsOK.Store(true)
  147. s.ctlOK.Store(true)
  148. go func() {
  149. err := obs.Serve(ol)
  150. s.obsOK.Store(false)
  151. if err != nil && !errors.Is(err, grpc.ErrServerStopped) {
  152. setHealth(ho, ObserveHealthService, healthpb.HealthCheckResponse_NOT_SERVING)
  153. select {
  154. case s.ErrC <- fmt.Errorf("observe grpc Serve: %w", err):
  155. default:
  156. }
  157. }
  158. }()
  159. go func() {
  160. err := ctl.Serve(cl)
  161. s.ctlOK.Store(false)
  162. if err != nil && !errors.Is(err, grpc.ErrServerStopped) {
  163. setHealth(hc, ControlHealthService, healthpb.HealthCheckResponse_NOT_SERVING)
  164. select {
  165. case s.ErrC <- fmt.Errorf("control grpc Serve: %w", err):
  166. default:
  167. }
  168. }
  169. }()
  170. return s, nil
  171. }
  172. func (s *Servers) ObserveAlive() bool {
  173. return s != nil && s.obsOK.Load()
  174. }
  175. func (s *Servers) ControlAlive() bool {
  176. return s != nil && s.ctlOK.Load()
  177. }
  178. func (s *Servers) Stop() {
  179. if s == nil {
  180. return
  181. }
  182. s.once.Do(func() {
  183. if s.healthO != nil {
  184. setHealth(s.healthO, ObserveHealthService, healthpb.HealthCheckResponse_NOT_SERVING)
  185. }
  186. if s.healthC != nil {
  187. setHealth(s.healthC, ControlHealthService, healthpb.HealthCheckResponse_NOT_SERVING)
  188. }
  189. done := make(chan struct{})
  190. go func() {
  191. if s.Observe != nil {
  192. s.Observe.GracefulStop()
  193. }
  194. if s.Control != nil {
  195. s.Control.GracefulStop()
  196. }
  197. close(done)
  198. }()
  199. select {
  200. case <-done:
  201. case <-time.After(2 * time.Second):
  202. if s.Observe != nil {
  203. s.Observe.Stop()
  204. }
  205. if s.Control != nil {
  206. s.Control.Stop()
  207. }
  208. }
  209. })
  210. }
  211. func (o *observeSrv) ListDevices(ctx context.Context, _ *hthv1.ListDevicesRequest) (*hthv1.ListDevicesResponse, error) {
  212. return o.api.ListDevices(ctx)
  213. }
  214. func (o *observeSrv) GetCapabilities(ctx context.Context, req *hthv1.GetCapabilitiesRequest) (*hthv1.GetCapabilitiesResponse, error) {
  215. c, err := o.api.Capabilities(ctx, req.DeviceId)
  216. if err != nil {
  217. return nil, err
  218. }
  219. return &hthv1.GetCapabilitiesResponse{Capabilities: c}, nil
  220. }
  221. func (o *observeSrv) GetSnapshot(ctx context.Context, req *hthv1.GetSnapshotRequest) (*hthv1.GetSnapshotResponse, error) {
  222. s, err := o.api.Snapshot(ctx, req.DeviceId)
  223. if err != nil {
  224. return nil, err
  225. }
  226. return &hthv1.GetSnapshotResponse{Snapshot: s}, nil
  227. }
  228. func (o *observeSrv) SubscribeTelemetry(req *hthv1.SubscribeTelemetryRequest, stream hthv1.ObserveService_SubscribeTelemetryServer) error {
  229. return o.api.SubscribeTelemetry(stream.Context(), req.DeviceId, req.ResumeAfterEventId, stream.Send)
  230. }
  231. func (o *observeSrv) SubscribeEvents(req *hthv1.SubscribeEventsRequest, stream hthv1.ObserveService_SubscribeEventsServer) error {
  232. return o.api.SubscribeEvents(stream.Context(), req.DeviceId, req.ResumeAfterEventId, stream.Send)
  233. }
  234. func (o *observeSrv) GetFaults(ctx context.Context, req *hthv1.GetFaultsRequest) (*hthv1.GetFaultsResponse, error) {
  235. return o.api.Faults(ctx, req.DeviceId, req.IncludeInactive)
  236. }
  237. func (o *observeSrv) WatchHealth(_ *hthv1.WatchHealthRequest, stream hthv1.ObserveService_WatchHealthServer) error {
  238. return o.api.WatchHealth(stream.Context(), stream.Send)
  239. }
  240. func (o *observeSrv) StepReplay(ctx context.Context, req *hthv1.StepReplayRequest) (*hthv1.StepReplayResponse, error) {
  241. return o.api.StepReplayObserve(ctx, req.GetDeviceId())
  242. }
  243. func (c *controlSrv) StepReplay(ctx context.Context, req *hthv1.StepReplayRequest) (*hthv1.StepReplayResponse, error) {
  244. return c.api.StepReplay(ctx, req.GetDeviceId())
  245. }
  246. func (c *controlSrv) AcquireControlLease(ctx context.Context, req *hthv1.AcquireControlLeaseRequest) (*hthv1.LeaseResponse, error) {
  247. l, err := c.api.AcquireLease(ctx, req)
  248. if err != nil {
  249. return nil, status.Error(codes.FailedPrecondition, err.Error())
  250. }
  251. return &hthv1.LeaseResponse{Lease: l}, nil
  252. }
  253. func (c *controlSrv) RenewControlLease(ctx context.Context, req *hthv1.RenewControlLeaseRequest) (*hthv1.LeaseResponse, error) {
  254. l, err := c.api.RenewLease(ctx, req)
  255. if err != nil {
  256. return nil, status.Error(codes.FailedPrecondition, err.Error())
  257. }
  258. return &hthv1.LeaseResponse{Lease: l}, nil
  259. }
  260. func (c *controlSrv) ReleaseControlLease(ctx context.Context, req *hthv1.ReleaseControlLeaseRequest) (*hthv1.LeaseResponse, error) {
  261. if err := c.api.ReleaseLease(ctx, req); err != nil {
  262. return nil, status.Error(codes.FailedPrecondition, err.Error())
  263. }
  264. return &hthv1.LeaseResponse{}, nil
  265. }
  266. func (c *controlSrv) ValidateAction(ctx context.Context, req *hthv1.ValidateActionRequest) (*hthv1.ActionResult, error) {
  267. return c.api.ValidateAction(ctx, req.Batch)
  268. }
  269. func (c *controlSrv) ApplyAction(ctx context.Context, req *hthv1.ApplyActionRequest) (*hthv1.ActionResult, error) {
  270. return c.api.ApplyAction(ctx, req.Batch)
  271. }
  272. func (c *controlSrv) EnterSafeMode(ctx context.Context, req *hthv1.EnterSafeModeRequest) (*hthv1.ActionResult, error) {
  273. return c.api.EnterSafeMode(ctx, req)
  274. }
  275. func (c *controlSrv) ResumeFromSafe(ctx context.Context, req *hthv1.ResumeFromSafeRequest) (*hthv1.ActionResult, error) {
  276. return c.api.ResumeFromSafe(ctx, req)
  277. }
  278. func (o *thermalObserveSrv) GetSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error) {
  279. return o.api.GetThermalSnapshot(ctx, req)
  280. }
  281. func (o *thermalObserveSrv) CaptureSnapshot(ctx context.Context, req *hthv1.GetThermalSnapshotRequest) (*hthv1.GetThermalSnapshotResponse, error) {
  282. return o.api.CaptureThermalSnapshot(ctx, req)
  283. }
  284. func (c *thermalControlSrv) SetTarget(ctx context.Context, req *hthv1.SetThermalTargetRequest) (*hthv1.ThermalCommandResult, error) {
  285. return c.api.SetThermalTarget(ctx, req)
  286. }
  287. func (c *thermalControlSrv) Stop(ctx context.Context, req *hthv1.StopThermalRequest) (*hthv1.ThermalCommandResult, error) {
  288. return c.api.StopThermal(ctx, req)
  289. }
  290. func (c *thermalControlSrv) RunStimulus(ctx context.Context, req *hthv1.RunThermalStimulusRequest) (*hthv1.ThermalCommandResult, error) {
  291. return c.api.RunThermalStimulus(ctx, req)
  292. }
  293. func DialUnix(path string, timeout time.Duration) (*grpc.ClientConn, error) {
  294. conn, err := grpc.NewClient("unix://"+path,
  295. grpc.WithTransportCredentials(insecure.NewCredentials()),
  296. grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(4<<20)),
  297. )
  298. if err != nil {
  299. return nil, err
  300. }
  301. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  302. defer cancel()
  303. conn.Connect()
  304. for {
  305. st := conn.GetState()
  306. if st == connectivity.Ready {
  307. return conn, nil
  308. }
  309. if st == connectivity.Shutdown {
  310. _ = conn.Close()
  311. return nil, fmt.Errorf("grpc unix %s shutdown", path)
  312. }
  313. if !conn.WaitForStateChange(ctx, st) {
  314. _ = conn.Close()
  315. return nil, ctx.Err()
  316. }
  317. }
  318. }