frostfs-http-gw/main.go

117 lines
2.5 KiB
Go
Raw Normal View History

2019-11-06 12:33:46 +00:00
package main
import (
"context"
"crypto/ecdsa"
2019-11-06 12:33:46 +00:00
"time"
"github.com/labstack/echo/v4"
"github.com/nspcc-dev/neofs-proto/object"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/grpclog"
2019-11-06 12:33:46 +00:00
"google.golang.org/grpc/keepalive"
)
type config struct {
log *zap.Logger
timeout time.Duration
key *ecdsa.PrivateKey
2019-11-06 12:33:46 +00:00
cli object.ServiceClient
}
func main() {
v := settings()
2019-11-06 12:33:46 +00:00
log, err := newLogger(v)
if err != nil {
panic(err)
}
log.Info("running application", zap.String("version", v.GetString("app.version")))
var (
cfg = new(config)
grace = newGracefulContext(log)
)
if v.GetBool("verbose") {
grpclog.SetLoggerV2(
gRPCLogger(log))
}
2019-11-06 12:33:46 +00:00
cfg.log = log
cfg.key = fetchKey(log, v)
2019-11-06 12:33:46 +00:00
cfg.timeout = v.GetDuration("request_timeout")
2019-11-06 12:33:46 +00:00
ctx, cancel := context.WithTimeout(grace, v.GetDuration("connect_timeout"))
defer cancel()
conn, err := grpc.DialContext(ctx, v.GetString("neofs_address"),
grpc.WithBlock(),
2019-11-06 12:33:46 +00:00
grpc.WithInsecure(),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: v.GetDuration("keepalive.time"),
Timeout: v.GetDuration("keepalive.timeout"),
PermitWithoutStream: v.GetBool("keepalive.permit_without_stream"),
}),
)
if err != nil {
log.Panic("could not connect to neofs-node",
zap.String("neofs-node", v.GetString("neofs_node_addr")),
zap.Error(err))
}
ctx, cancel = context.WithCancel(grace)
defer cancel()
go checkConnection(ctx, conn, log)
cfg.cli = object.NewServiceClient(conn)
e := echo.New()
e.Debug = false
e.HidePort = true
e.HideBanner = true
e.GET("/:cid/:oid", cfg.receiveFile)
2019-11-06 12:33:46 +00:00
go func() {
log.Info("run gateway server",
zap.String("address", v.GetString("listen_address")))
2019-11-06 12:33:46 +00:00
if err := e.Start(v.GetString("listen_address")); err != nil {
log.Panic("could not start server", zap.Error(err))
}
}()
<-ctx.Done()
ctx, cancel = context.WithTimeout(context.TODO(), time.Second*30)
defer cancel()
log.Info("stopping server", zap.Error(e.Shutdown(ctx)))
2019-11-06 12:33:46 +00:00
}
func checkConnection(ctx context.Context, conn *grpc.ClientConn, log *zap.Logger) {
tick := time.NewTicker(time.Second)
loop:
for {
select {
case <-ctx.Done():
break loop
case <-tick.C:
switch state := conn.GetState(); state {
case connectivity.Idle, connectivity.Connecting, connectivity.Ready:
// It's ok..
default:
log.Error("could not establish connection",
2019-11-06 12:33:46 +00:00
zap.Stringer("state", state),
zap.Any("connection", conn.Target()))
}
}
}
tick.Stop()
}