blob: 20c3a3a1ee6649df3c7c7dfea30123590ea1d3ad [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"
23 "git.monogon.dev/source/nexantic.git/core/internal/consensus"
24 "github.com/casbin/casbin"
25 "go.uber.org/zap"
26 "google.golang.org/grpc"
27 "net"
28)
29
30type (
31 Server struct {
32 *common.BaseService
33
34 ruleEnforcer *casbin.Enforcer
35 setupService common.SetupService
36 grpcServer *grpc.Server
37
38 consensusService *consensus.Service
39
40 config *Config
41 }
42
43 Config struct {
44 Port uint16
45 }
46)
47
48func NewApiServer(config *Config, logger *zap.Logger, setupService common.SetupService, consensusService *consensus.Service) (*Server, error) {
49 s := &Server{
50 config: config,
51 setupService: setupService,
52 consensusService: consensusService,
53 }
54
55 s.BaseService = common.NewBaseService("api", logger, s)
56
57 grpcServer := grpc.NewServer()
58 schema.RegisterClusterManagementServer(grpcServer, s)
59 schema.RegisterSetupServiceServer(grpcServer, s)
60
61 s.grpcServer = grpcServer
62
63 return s, nil
64}
65
66func (s *Server) OnStart() error {
67 listenHost := fmt.Sprintf(":%d", s.config.Port)
68 lis, err := net.Listen("tcp", listenHost)
69 if err != nil {
70 s.Logger.Fatal("failed to listen", zap.Error(err))
71 }
72
73 go func() {
74 err = s.grpcServer.Serve(lis)
75 s.Logger.Error("API server failed", zap.Error(err))
76 }()
77
78 s.Logger.Info("GRPC listening", zap.String("host", listenHost))
79
80 return nil
81}
82
83func (s *Server) OnStop() error {
84 s.grpcServer.Stop()
85
86 return nil
87}