blob: 715e99e752d23e964c7ca773475cdf21b6903f31 [file] [log] [blame]
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package api
18
19import (
20 "fmt"
21 schema "git.monogon.dev/source/nexantic.git/core/generated/api"
22 "git.monogon.dev/source/nexantic.git/core/internal/common"
Leopold Schabel68c58752019-11-14 21:00:59 +010023 "git.monogon.dev/source/nexantic.git/core/internal/common/service"
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +020024 "git.monogon.dev/source/nexantic.git/core/internal/consensus"
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +020025 "go.uber.org/zap"
26 "google.golang.org/grpc"
27 "net"
28)
29
30type (
31 Server struct {
Leopold Schabel68c58752019-11-14 21:00:59 +010032 *service.BaseService
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +020033
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +020034 setupService common.SetupService
35 grpcServer *grpc.Server
36
37 consensusService *consensus.Service
38
39 config *Config
40 }
41
42 Config struct {
43 Port uint16
44 }
45)
46
47func NewApiServer(config *Config, logger *zap.Logger, setupService common.SetupService, consensusService *consensus.Service) (*Server, error) {
48 s := &Server{
49 config: config,
50 setupService: setupService,
51 consensusService: consensusService,
52 }
53
Leopold Schabel68c58752019-11-14 21:00:59 +010054 s.BaseService = service.NewBaseService("api", logger, s)
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +020055
56 grpcServer := grpc.NewServer()
57 schema.RegisterClusterManagementServer(grpcServer, s)
58 schema.RegisterSetupServiceServer(grpcServer, s)
59
60 s.grpcServer = grpcServer
61
62 return s, nil
63}
64
65func (s *Server) OnStart() error {
66 listenHost := fmt.Sprintf(":%d", s.config.Port)
67 lis, err := net.Listen("tcp", listenHost)
68 if err != nil {
69 s.Logger.Fatal("failed to listen", zap.Error(err))
70 }
71
72 go func() {
73 err = s.grpcServer.Serve(lis)
74 s.Logger.Error("API server failed", zap.Error(err))
75 }()
76
Leopold Schabel68c58752019-11-14 21:00:59 +010077 s.Logger.Info("gRPC listening", zap.String("host", listenHost))
Hendrik Hofstadt0d7c91e2019-10-23 21:44:47 +020078
79 return nil
80}
81
82func (s *Server) OnStop() error {
83 s.grpcServer.Stop()
84
85 return nil
86}