225 lines
5.3 KiB
Go
225 lines
5.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
|
|
"micro_layout/cmd/srv/config"
|
|
"micro_layout/internal/configs"
|
|
"micro_layout/internal/logger"
|
|
"micro_layout/internal/logic"
|
|
"micro_layout/internal/queue/jetstream"
|
|
"micro_layout/internal/runtime/monitor"
|
|
"micro_layout/internal/server"
|
|
"micro_layout/internal/storage"
|
|
|
|
"git.vitatech.com.cn/leo/proto.git/discovery"
|
|
"git.vitatech.com.cn/leo/proto.git/micro_layout/proto/user"
|
|
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
|
|
"github.com/nats-io/nats.go"
|
|
log "github.com/sirupsen/logrus"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/health"
|
|
"google.golang.org/grpc/health/grpc_health_v1"
|
|
"google.golang.org/grpc/reflection"
|
|
)
|
|
|
|
var (
|
|
host string
|
|
logPath string
|
|
configPath string
|
|
conf *config.Config
|
|
wg *sync.WaitGroup
|
|
runtimeStop chan error
|
|
)
|
|
|
|
func runServer(ctx context.Context) error {
|
|
defer wg.Done()
|
|
|
|
srv := grpc.NewServer(
|
|
grpc.UnaryInterceptor(server.UnaryRecovery),
|
|
grpc.StreamInterceptor(server.StreamRecovery),
|
|
)
|
|
defer srv.Stop()
|
|
user.RegisterUserServer(srv, &server.UserServer{})
|
|
healthServer := health.NewServer()
|
|
grpc_health_v1.RegisterHealthServer(srv, healthServer)
|
|
if conf.Server.Reflection {
|
|
reflection.Register(srv)
|
|
}
|
|
|
|
listener, err := net.Listen("tcp", conf.Server.Addr)
|
|
if err != nil {
|
|
return fmt.Errorf("listen: %w", err)
|
|
}
|
|
defer listener.Close()
|
|
|
|
address := conf.Registry.AdvertiseAddr
|
|
if address == "" {
|
|
_, port, err := net.SplitHostPort(listener.Addr().String())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
address = net.JoinHostPort(host, port)
|
|
}
|
|
registration, err := discovery.Register(ctx, conf.Registry.Etcd, conf.Registry.ServiceName, address, conf.Registry.LeaseTTL)
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("etcd register: %w", err)
|
|
}
|
|
defer func() {
|
|
healthServer.Shutdown()
|
|
if err := registration.Close(); err != nil {
|
|
log.WithError(err).Warn("unregister service")
|
|
}
|
|
stopped := make(chan struct{})
|
|
go func() {
|
|
srv.GracefulStop()
|
|
close(stopped)
|
|
}()
|
|
timer := time.NewTimer(conf.Server.ShutdownTimeout)
|
|
defer timer.Stop()
|
|
select {
|
|
case <-stopped:
|
|
case <-timer.C:
|
|
srv.Stop()
|
|
<-stopped
|
|
}
|
|
}()
|
|
|
|
healthServer.SetServingStatus("", grpc_health_v1.HealthCheckResponse_SERVING)
|
|
log.WithFields(log.Fields{"service_name": conf.Registry.ServiceName, "address": address}).Info("service registered")
|
|
log.Infof("grpc start: %s", listener.Addr())
|
|
defer log.Info("grpc exit")
|
|
serverErrors := make(chan error, 1)
|
|
go func() { serverErrors <- srv.Serve(listener) }()
|
|
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil
|
|
case <-registration.Done():
|
|
if ctx.Err() != nil {
|
|
return nil
|
|
}
|
|
return errors.New("etcd registration keepalive stopped")
|
|
case err := <-serverErrors:
|
|
if errors.Is(err, grpc.ErrServerStopped) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
}
|
|
|
|
func runMonitor(ctx context.Context) error {
|
|
defer wg.Done()
|
|
|
|
m := monitor.NewMonitor()
|
|
if err := m.Init(); err != nil {
|
|
return err
|
|
}
|
|
go func() {
|
|
<-ctx.Done()
|
|
if err := m.Stop(); err != nil {
|
|
log.WithError(err).Error("monitor stop")
|
|
}
|
|
}()
|
|
return m.Start()
|
|
}
|
|
|
|
func run() error {
|
|
conf = &config.Config{}
|
|
if err := configs.Load(configPath, conf); err != nil {
|
|
return fmt.Errorf("config load: %w", err)
|
|
}
|
|
if err := logger.Setup(conf.Log.Level, conf.App.Name, conf.App.Env); err != nil {
|
|
return err
|
|
}
|
|
|
|
var jetStreamBr nats.JetStreamContext
|
|
if conf.JetStream.Enabled {
|
|
broker, err := jetstream.NewJetStreamBroker(conf.JetStream)
|
|
if err != nil {
|
|
return fmt.Errorf("NewJetStreamBroker: %w", err)
|
|
}
|
|
defer broker.Close()
|
|
jetStreamBr = broker
|
|
}
|
|
st, err := storage.NewStorage(conf.Storage)
|
|
if err != nil {
|
|
return fmt.Errorf("NewStorage: %w", err)
|
|
}
|
|
defer func() {
|
|
if err := st.Close(); err != nil {
|
|
log.WithError(err).Error("close storage")
|
|
}
|
|
}()
|
|
if err := logic.Init(
|
|
logic.WithEnv(conf.App.Env),
|
|
logic.WithStorage(st),
|
|
logic.WithJetStreamBroker(jetStreamBr),
|
|
); err != nil {
|
|
return fmt.Errorf("logic.Init: %w", err)
|
|
}
|
|
|
|
wg = &sync.WaitGroup{}
|
|
runtimeStop = make(chan error, 2)
|
|
runtimeCtx, runtimeCancel := context.WithCancel(context.Background())
|
|
defer func() {
|
|
runtimeCancel()
|
|
wg.Wait()
|
|
}()
|
|
wg.Add(2)
|
|
go func() {
|
|
err := runServer(runtimeCtx)
|
|
if err != nil {
|
|
log.WithError(err).Error("run server")
|
|
}
|
|
runtimeStop <- err
|
|
}()
|
|
go func() {
|
|
err := runMonitor(runtimeCtx)
|
|
if err != nil {
|
|
log.WithError(err).Error("run monitor")
|
|
}
|
|
runtimeStop <- err
|
|
}()
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
|
defer stop()
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil
|
|
case err := <-runtimeStop:
|
|
return err
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
flag.StringVar(&logPath, "logPath", "./logs", "日志目录")
|
|
flag.StringVar(&configPath, "config", "", "配置文件地址,默认 CONFIG_FILE 或 ./configs/config.yaml")
|
|
flag.StringVar(&host, "host", "127.0.0.1", "本机 IP,未配置 registry.advertise_addr 时使用")
|
|
flag.Parse()
|
|
|
|
writer, err := rotatelogs.New(filepath.Join(logPath, "micro_layout_srv_%Y%m%d.log"), rotatelogs.WithMaxAge(72*time.Hour))
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer writer.Close()
|
|
log.SetOutput(io.MultiWriter(os.Stdout, writer))
|
|
if err := run(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|