274 lines
7.0 KiB
Go
Raw Normal View History

2021-01-03 18:15:44 +05:30
package app
import (
"context"
2021-05-22 19:51:56 +05:30
"fmt"
2021-01-03 18:15:44 +05:30
"net"
"net/http"
_ "net/http/pprof" // http profiler
2021-05-22 19:51:56 +05:30
"os"
2021-01-09 19:10:34 +05:30
"time"
2021-01-03 18:15:44 +05:30
"github.com/gorilla/handlers"
2021-01-09 19:10:34 +05:30
"github.com/gorilla/mux"
2021-03-01 02:43:05 +05:30
"github.com/rs/cors"
2021-01-03 18:15:44 +05:30
"github.com/soheilhy/cmux"
2021-05-27 12:52:34 +05:30
"go.signoz.io/query-service/app/clickhouseReader"
"go.signoz.io/query-service/app/dashboards"
"go.signoz.io/query-service/constants"
"go.signoz.io/query-service/dao"
2021-01-03 18:15:44 +05:30
"go.signoz.io/query-service/healthcheck"
"go.signoz.io/query-service/telemetry"
2021-01-03 18:15:44 +05:30
"go.signoz.io/query-service/utils"
"go.uber.org/zap"
)
type ServerOptions struct {
2021-05-22 19:51:56 +05:30
HTTPHostPort string
// DruidClientUrl string
2021-01-03 18:15:44 +05:30
}
// Server runs HTTP, Mux and a grpc server
type Server struct {
// logger *zap.Logger
// querySvc *querysvc.QueryService
// queryOptions *QueryOptions
// tracer opentracing.Tracer // TODO make part of flags.Service
2021-05-22 19:51:56 +05:30
serverOptions *ServerOptions
conn net.Listener
2021-01-03 18:15:44 +05:30
// grpcConn net.Listener
httpConn net.Listener
// grpcServer *grpc.Server
httpServer *http.Server
separatePorts bool
unavailableChannel chan healthcheck.Status
}
// HealthCheckStatus returns health check status channel a client can subscribe to
func (s Server) HealthCheckStatus() chan healthcheck.Status {
return s.unavailableChannel
}
// NewServer creates and initializes Server
// func NewServer(logger *zap.Logger, querySvc *querysvc.QueryService, options *QueryOptions, tracer opentracing.Tracer) (*Server, error) {
func NewServer(serverOptions *ServerOptions) (*Server, error) {
// _, httpPort, err := net.SplitHostPort(serverOptions.HTTPHostPort)
// if err != nil {
// return nil, err
// }
// _, grpcPort, err := net.SplitHostPort(options.GRPCHostPort)
// if err != nil {
// return nil, err
// }
// grpcServer, err := createGRPCServer(querySvc, options, logger, tracer)
// if err != nil {
// return nil, err
// }
if err := dao.InitDao("sqlite", constants.RELATIONAL_DATASOURCE_PATH); err != nil {
return nil, err
}
s := &Server{
2021-01-03 18:15:44 +05:30
// logger: logger,
// querySvc: querySvc,
// queryOptions: options,
// tracer: tracer,
// grpcServer: grpcServer,
serverOptions: serverOptions,
separatePorts: true,
// separatePorts: grpcPort != httpPort,
unavailableChannel: make(chan healthcheck.Status),
}
httpServer, err := s.createHTTPServer()
2021-01-03 18:15:44 +05:30
if err != nil {
return nil, err
}
s.httpServer = httpServer
2021-01-09 19:10:34 +05:30
return s, nil
}
2021-01-03 18:15:44 +05:30
func (s *Server) createHTTPServer() (*http.Server, error) {
2021-01-09 19:10:34 +05:30
localDB, err := dashboards.InitDB(constants.RELATIONAL_DATASOURCE_PATH)
if err != nil {
return nil, err
}
localDB.SetMaxOpenConns(10)
2021-05-22 19:51:56 +05:30
var reader Reader
storage := os.Getenv("STORAGE")
if storage == "druid" {
zap.S().Info("Using Apache Druid as datastore ...")
// reader = druidReader.NewReader(localDB)
2021-05-22 19:51:56 +05:30
} else if storage == "clickhouse" {
zap.S().Info("Using ClickHouse as datastore ...")
clickhouseReader := clickhouseReader.NewReader(localDB)
go clickhouseReader.Start()
reader = clickhouseReader
2021-05-22 19:51:56 +05:30
} else {
return nil, fmt.Errorf("Storage type: %s is not supported in query service", storage)
2021-01-03 18:15:44 +05:30
}
apiHandler, err := NewAPIHandler(&reader, dao.DB())
if err != nil {
return nil, err
}
2021-01-03 18:15:44 +05:30
r := NewRouter()
r.Use(setTimeoutMiddleware)
r.Use(s.analyticsMiddleware)
2021-01-09 19:10:34 +05:30
r.Use(loggingMiddleware)
2021-01-03 18:15:44 +05:30
apiHandler.RegisterRoutes(r)
apiHandler.RegisterMetricsRoutes(r)
2021-01-03 18:15:44 +05:30
2021-03-01 02:43:05 +05:30
c := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
// AllowCredentials: true,
2021-09-02 14:55:07 +05:30
AllowedMethods: []string{"GET", "DELETE", "POST", "PUT"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type"},
2021-03-01 02:43:05 +05:30
})
2021-01-03 18:15:44 +05:30
2021-03-01 02:43:05 +05:30
handler := c.Handler(r)
// var handler http.Handler = r
2021-01-03 18:15:44 +05:30
handler = handlers.CompressHandler(handler)
return &http.Server{
Handler: handler,
2021-05-22 19:51:56 +05:30
}, nil
2021-01-03 18:15:44 +05:30
}
2021-01-09 19:10:34 +05:30
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
startTime := time.Now()
next.ServeHTTP(w, r)
zap.S().Info(path, "\ttimeTaken: ", time.Now().Sub(startTime))
})
}
func (s *Server) analyticsMiddleware(next http.Handler) http.Handler {
2021-01-09 19:10:34 +05:30
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
data := map[string]interface{}{"path": path}
if _, ok := telemetry.IgnoredPaths()[path]; !ok {
telemetry.GetInstance().SendEvent(telemetry.TELEMETRY_EVENT_PATH, data)
}
2021-01-09 19:10:34 +05:30
next.ServeHTTP(w, r)
})
}
func setTimeoutMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), constants.ContextTimeout*time.Second)
defer cancel()
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
2021-01-03 18:15:44 +05:30
// initListener initialises listeners of the server
func (s *Server) initListener() (cmux.CMux, error) {
if s.separatePorts { // use separate ports and listeners each for gRPC and HTTP requests
var err error
// s.grpcConn, err = net.Listen("tcp", s.queryOptions.GRPCHostPort)
// if err != nil {
// return nil, err
// }
s.httpConn, err = net.Listen("tcp", s.serverOptions.HTTPHostPort)
if err != nil {
return nil, err
}
zap.S().Info("Query server started ...")
return nil, nil
}
// // old behavior using cmux
// conn, err := net.Listen("tcp", s.queryOptions.HostPort)
// if err != nil {
// return nil, err
// }
// s.conn = conn
// var tcpPort int
// if port, err := netutils
// utils.GetPort(s.conn.Addr()); err == nil {
// tcpPort = port
// }
// zap.S().Info(
// "Query server started",
// zap.Int("port", tcpPort),
// zap.String("addr", s.queryOptions.HostPort))
// // cmux server acts as a reverse-proxy between HTTP and GRPC backends.
// cmuxServer := cmux.New(s.conn)
// s.grpcConn = cmuxServer.MatchWithWriters(
// cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc"),
// cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc+proto"),
// )
// s.httpConn = cmuxServer.Match(cmux.Any())
// s.queryOptions.HTTPHostPort = s.queryOptions.HostPort
// s.queryOptions.GRPCHostPort = s.queryOptions.HostPort
return nil, nil
}
// Start http, GRPC and cmux servers concurrently
func (s *Server) Start() error {
_, err := s.initListener()
if err != nil {
return err
}
var httpPort int
if port, err := utils.GetPort(s.httpConn.Addr()); err == nil {
httpPort = port
}
go func() {
zap.S().Info("Starting HTTP server", zap.Int("port", httpPort), zap.String("addr", s.serverOptions.HTTPHostPort))
switch err := s.httpServer.Serve(s.httpConn); err {
case nil, http.ErrServerClosed, cmux.ErrListenerClosed:
// normal exit, nothing to do
default:
zap.S().Error("Could not start HTTP server", zap.Error(err))
}
s.unavailableChannel <- healthcheck.Unavailable
}()
go func() {
zap.S().Info("Starting pprof server", zap.String("addr", constants.DebugHttpPort))
2021-01-03 18:15:44 +05:30
err = http.ListenAndServe(constants.DebugHttpPort, nil)
if err != nil {
zap.S().Error("Could not start HTTP server", zap.Error(err))
}
2021-01-03 18:15:44 +05:30
}()
return nil
}