2016-12-21 07:36:32 -06:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2017-02-15 07:29:20 -06:00
|
|
|
"crypto/tls"
|
2020-11-19 06:34:28 -06:00
|
|
|
"errors"
|
2016-12-21 07:36:32 -06:00
|
|
|
"fmt"
|
2017-04-27 01:54:21 -05:00
|
|
|
"net"
|
2016-12-21 07:36:32 -06:00
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"path"
|
2020-10-19 10:35:31 -05:00
|
|
|
"path/filepath"
|
2021-02-15 10:55:41 -06:00
|
|
|
"strings"
|
2019-11-27 05:07:21 -06:00
|
|
|
"sync"
|
2016-12-21 07:36:32 -06:00
|
|
|
|
2019-01-16 07:53:59 -06:00
|
|
|
"github.com/grafana/grafana/pkg/api/routing"
|
2016-12-21 07:36:32 -06:00
|
|
|
httpstatic "github.com/grafana/grafana/pkg/api/static"
|
2017-04-25 10:17:45 -05:00
|
|
|
"github.com/grafana/grafana/pkg/bus"
|
|
|
|
"github.com/grafana/grafana/pkg/components/simplejson"
|
2019-06-13 03:55:38 -05:00
|
|
|
"github.com/grafana/grafana/pkg/infra/localcache"
|
2019-05-13 01:45:54 -05:00
|
|
|
"github.com/grafana/grafana/pkg/infra/log"
|
2019-04-08 06:31:46 -05:00
|
|
|
"github.com/grafana/grafana/pkg/infra/remotecache"
|
2021-08-25 08:11:22 -05:00
|
|
|
"github.com/grafana/grafana/pkg/infra/tracing"
|
2021-08-30 12:39:55 -05:00
|
|
|
"github.com/grafana/grafana/pkg/login/social"
|
2016-12-21 07:36:32 -06:00
|
|
|
"github.com/grafana/grafana/pkg/middleware"
|
2017-04-25 10:17:45 -05:00
|
|
|
"github.com/grafana/grafana/pkg/models"
|
2021-03-22 07:22:48 -05:00
|
|
|
"github.com/grafana/grafana/pkg/plugins"
|
2021-03-23 12:24:08 -05:00
|
|
|
"github.com/grafana/grafana/pkg/plugins/plugincontext"
|
2021-04-06 08:49:09 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/accesscontrol"
|
2021-12-14 09:05:59 -06:00
|
|
|
acmiddleware "github.com/grafana/grafana/pkg/services/accesscontrol/middleware"
|
2022-01-26 08:48:41 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/accesscontrol/resourcepermissions"
|
|
|
|
"github.com/grafana/grafana/pkg/services/accesscontrol/resourceservices"
|
2021-03-22 07:22:48 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/alerting"
|
2021-08-30 12:39:55 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/cleanup"
|
2020-12-11 04:44:44 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/contexthandler"
|
2021-03-17 12:10:40 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/datasourceproxy"
|
2018-10-26 03:40:33 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/datasources"
|
2021-08-30 12:39:55 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/encryption"
|
2022-01-26 11:44:20 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/featuremgmt"
|
2018-10-12 04:26:42 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/hooks"
|
2022-02-01 05:03:21 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/ldap"
|
2021-08-30 12:39:55 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/libraryelements"
|
|
|
|
"github.com/grafana/grafana/pkg/services/librarypanels"
|
2021-03-22 07:22:48 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/live"
|
2021-04-26 05:17:49 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/live/pushhttp"
|
2019-06-13 09:47:52 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/login"
|
2021-08-30 12:39:55 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/ngalert"
|
2022-02-03 03:33:46 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/notifications"
|
2020-03-25 08:14:24 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/provisioning"
|
2022-01-26 08:48:41 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/query"
|
2022-01-28 10:55:09 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/queryhistory"
|
2019-02-11 14:12:01 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/quota"
|
2018-05-24 08:26:27 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/rendering"
|
2021-04-28 06:38:33 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/schemaloader"
|
2021-03-22 07:22:48 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/search"
|
2021-11-01 04:53:33 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/searchusers"
|
2021-11-04 11:47:21 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/secrets"
|
2022-01-26 08:48:41 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/serviceaccounts"
|
2021-03-22 07:22:48 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/shorturls"
|
|
|
|
"github.com/grafana/grafana/pkg/services/sqlstore"
|
2022-01-07 06:38:00 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/teamguardian"
|
2022-01-26 08:48:41 -06:00
|
|
|
"github.com/grafana/grafana/pkg/services/thumbs"
|
2021-11-01 04:53:33 -05:00
|
|
|
"github.com/grafana/grafana/pkg/services/updatechecker"
|
2016-12-21 07:36:32 -06:00
|
|
|
"github.com/grafana/grafana/pkg/setting"
|
2021-05-11 00:10:19 -05:00
|
|
|
"github.com/grafana/grafana/pkg/util/errutil"
|
2021-10-11 07:30:59 -05:00
|
|
|
"github.com/grafana/grafana/pkg/web"
|
2021-03-23 12:24:08 -05:00
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2016-12-21 07:36:32 -06:00
|
|
|
)
|
|
|
|
|
2018-03-22 16:13:46 -05:00
|
|
|
type HTTPServer struct {
|
2022-01-24 07:41:18 -06:00
|
|
|
log log.Logger
|
|
|
|
web *web.Mux
|
|
|
|
context context.Context
|
|
|
|
httpSrv *http.Server
|
|
|
|
middlewares []web.Handler
|
|
|
|
namedMiddlewares []routing.RegisterNamedMiddleware
|
2017-02-06 02:40:07 -06:00
|
|
|
|
2022-02-09 07:01:32 -06:00
|
|
|
PluginContextProvider *plugincontext.Provider
|
|
|
|
RouteRegister routing.RouteRegister
|
|
|
|
Bus bus.Bus
|
|
|
|
RenderService rendering.Service
|
|
|
|
Cfg *setting.Cfg
|
|
|
|
Features *featuremgmt.FeatureManager
|
|
|
|
SettingsProvider setting.Provider
|
|
|
|
HooksService *hooks.HooksService
|
|
|
|
CacheService *localcache.CacheService
|
|
|
|
DataSourceCache datasources.CacheService
|
|
|
|
AuthTokenService models.UserTokenService
|
|
|
|
QuotaService *quota.QuotaService
|
|
|
|
RemoteCacheService *remotecache.RemoteCache
|
|
|
|
ProvisioningService provisioning.ProvisioningService
|
|
|
|
Login login.Service
|
|
|
|
License models.Licensing
|
|
|
|
AccessControl accesscontrol.AccessControl
|
|
|
|
DataProxy *datasourceproxy.DataSourceProxyService
|
|
|
|
PluginRequestValidator models.PluginRequestValidator
|
|
|
|
pluginClient plugins.Client
|
|
|
|
pluginStore plugins.Store
|
|
|
|
pluginDashboardManager plugins.PluginDashboardManager
|
|
|
|
pluginStaticRouteResolver plugins.StaticRouteResolver
|
|
|
|
pluginErrorResolver plugins.ErrorResolver
|
|
|
|
SearchService search.Service
|
|
|
|
ShortURLService shorturls.Service
|
|
|
|
QueryHistoryService queryhistory.Service
|
|
|
|
Live *live.GrafanaLive
|
|
|
|
LivePushGateway *pushhttp.Gateway
|
|
|
|
ThumbService thumbs.Service
|
|
|
|
ContextHandler *contexthandler.ContextHandler
|
|
|
|
SQLStore sqlstore.Store
|
|
|
|
AlertEngine *alerting.AlertEngine
|
|
|
|
LoadSchemaService *schemaloader.SchemaLoaderService
|
|
|
|
AlertNG *ngalert.AlertNG
|
|
|
|
LibraryPanelService librarypanels.Service
|
|
|
|
LibraryElementService libraryelements.Service
|
|
|
|
SocialService social.Service
|
|
|
|
Listener net.Listener
|
|
|
|
EncryptionService encryption.Internal
|
|
|
|
SecretsService secrets.Service
|
|
|
|
DataSourcesService *datasources.Service
|
|
|
|
cleanUpService *cleanup.CleanUpService
|
|
|
|
tracer tracing.Tracer
|
|
|
|
grafanaUpdateChecker *updatechecker.GrafanaService
|
|
|
|
pluginsUpdateChecker *updatechecker.PluginsService
|
|
|
|
searchUsersService searchusers.Service
|
|
|
|
ldapGroups ldap.Groups
|
|
|
|
teamGuardian teamguardian.TeamGuardian
|
|
|
|
queryDataService *query.Service
|
|
|
|
serviceAccountsService serviceaccounts.Service
|
|
|
|
authInfoService login.AuthInfoService
|
|
|
|
TeamPermissionsService *resourcepermissions.Service
|
|
|
|
NotificationService *notifications.NotificationService
|
|
|
|
DatasourcePermissionsService DatasourcePermissionsService
|
2021-08-25 08:11:22 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
type ServerOptions struct {
|
|
|
|
Listener net.Listener
|
2016-12-21 07:36:32 -06:00
|
|
|
}
|
|
|
|
|
2021-08-25 08:11:22 -05:00
|
|
|
func ProvideHTTPServer(opts ServerOptions, cfg *setting.Cfg, routeRegister routing.RouteRegister, bus bus.Bus,
|
|
|
|
renderService rendering.Service, licensing models.Licensing, hooksService *hooks.HooksService,
|
2021-11-29 07:21:54 -06:00
|
|
|
cacheService *localcache.CacheService, sqlStore *sqlstore.SQLStore, alertEngine *alerting.AlertEngine,
|
2021-11-01 04:53:33 -05:00
|
|
|
pluginRequestValidator models.PluginRequestValidator, pluginStaticRouteResolver plugins.StaticRouteResolver,
|
|
|
|
pluginDashboardManager plugins.PluginDashboardManager, pluginStore plugins.Store, pluginClient plugins.Client,
|
|
|
|
pluginErrorResolver plugins.ErrorResolver, settingsProvider setting.Provider,
|
2021-08-25 08:11:22 -05:00
|
|
|
dataSourceCache datasources.CacheService, userTokenService models.UserTokenService,
|
2022-01-28 10:55:09 -06:00
|
|
|
cleanUpService *cleanup.CleanUpService, shortURLService shorturls.Service, queryHistoryService queryhistory.Service,
|
|
|
|
thumbService thumbs.Service, remoteCache *remotecache.RemoteCache, provisioningService provisioning.ProvisioningService,
|
2021-08-25 08:11:22 -05:00
|
|
|
loginService login.Service, accessControl accesscontrol.AccessControl,
|
|
|
|
dataSourceProxy *datasourceproxy.DataSourceProxyService, searchService *search.SearchService,
|
|
|
|
live *live.GrafanaLive, livePushGateway *pushhttp.Gateway, plugCtxProvider *plugincontext.Provider,
|
2022-01-26 11:44:20 -06:00
|
|
|
contextHandler *contexthandler.ContextHandler, features *featuremgmt.FeatureManager,
|
2021-08-25 08:11:22 -05:00
|
|
|
schemaService *schemaloader.SchemaLoaderService, alertNG *ngalert.AlertNG,
|
|
|
|
libraryPanelService librarypanels.Service, libraryElementService libraryelements.Service,
|
2022-01-20 04:10:12 -06:00
|
|
|
quotaService *quota.QuotaService, socialService social.Service, tracer tracing.Tracer,
|
2022-01-31 09:06:16 -06:00
|
|
|
encryptionService encryption.Internal, grafanaUpdateChecker *updatechecker.GrafanaService,
|
|
|
|
pluginsUpdateChecker *updatechecker.PluginsService, searchUsersService searchusers.Service,
|
2022-01-07 06:38:00 -06:00
|
|
|
dataSourcesService *datasources.Service, secretsService secrets.Service, queryDataService *query.Service,
|
2022-02-01 05:03:21 -06:00
|
|
|
ldapGroups ldap.Groups, teamGuardian teamguardian.TeamGuardian, serviceaccountsService serviceaccounts.Service,
|
2022-02-03 11:23:45 -06:00
|
|
|
authInfoService login.AuthInfoService, resourcePermissionServices *resourceservices.ResourceServices,
|
2022-02-09 07:01:32 -06:00
|
|
|
notificationService *notifications.NotificationService, datasourcePermissionsService DatasourcePermissionsService) (*HTTPServer, error) {
|
2021-10-11 07:30:59 -05:00
|
|
|
web.Env = cfg.Env
|
|
|
|
m := web.New()
|
2018-05-01 08:51:15 -05:00
|
|
|
|
2021-08-25 08:11:22 -05:00
|
|
|
hs := &HTTPServer{
|
2022-02-09 07:01:32 -06:00
|
|
|
Cfg: cfg,
|
|
|
|
RouteRegister: routeRegister,
|
|
|
|
Bus: bus,
|
|
|
|
RenderService: renderService,
|
|
|
|
License: licensing,
|
|
|
|
HooksService: hooksService,
|
|
|
|
CacheService: cacheService,
|
|
|
|
SQLStore: sqlStore,
|
|
|
|
AlertEngine: alertEngine,
|
|
|
|
PluginRequestValidator: pluginRequestValidator,
|
|
|
|
pluginClient: pluginClient,
|
|
|
|
pluginStore: pluginStore,
|
|
|
|
pluginStaticRouteResolver: pluginStaticRouteResolver,
|
|
|
|
pluginDashboardManager: pluginDashboardManager,
|
|
|
|
pluginErrorResolver: pluginErrorResolver,
|
|
|
|
grafanaUpdateChecker: grafanaUpdateChecker,
|
|
|
|
pluginsUpdateChecker: pluginsUpdateChecker,
|
|
|
|
SettingsProvider: settingsProvider,
|
|
|
|
DataSourceCache: dataSourceCache,
|
|
|
|
AuthTokenService: userTokenService,
|
|
|
|
cleanUpService: cleanUpService,
|
|
|
|
ShortURLService: shortURLService,
|
|
|
|
QueryHistoryService: queryHistoryService,
|
|
|
|
Features: features,
|
|
|
|
ThumbService: thumbService,
|
|
|
|
RemoteCacheService: remoteCache,
|
|
|
|
ProvisioningService: provisioningService,
|
|
|
|
Login: loginService,
|
|
|
|
AccessControl: accessControl,
|
|
|
|
DataProxy: dataSourceProxy,
|
|
|
|
SearchService: searchService,
|
|
|
|
Live: live,
|
|
|
|
LivePushGateway: livePushGateway,
|
|
|
|
PluginContextProvider: plugCtxProvider,
|
|
|
|
ContextHandler: contextHandler,
|
|
|
|
LoadSchemaService: schemaService,
|
|
|
|
AlertNG: alertNG,
|
|
|
|
LibraryPanelService: libraryPanelService,
|
|
|
|
LibraryElementService: libraryElementService,
|
|
|
|
QuotaService: quotaService,
|
|
|
|
tracer: tracer,
|
|
|
|
log: log.New("http.server"),
|
|
|
|
web: m,
|
|
|
|
Listener: opts.Listener,
|
|
|
|
SocialService: socialService,
|
|
|
|
EncryptionService: encryptionService,
|
|
|
|
SecretsService: secretsService,
|
|
|
|
DataSourcesService: dataSourcesService,
|
|
|
|
searchUsersService: searchUsersService,
|
|
|
|
ldapGroups: ldapGroups,
|
|
|
|
teamGuardian: teamGuardian,
|
|
|
|
queryDataService: queryDataService,
|
|
|
|
serviceAccountsService: serviceaccountsService,
|
|
|
|
authInfoService: authInfoService,
|
|
|
|
TeamPermissionsService: resourcePermissionServices.GetTeamService(),
|
|
|
|
NotificationService: notificationService,
|
|
|
|
DatasourcePermissionsService: datasourcePermissionsService,
|
2021-08-25 08:11:22 -05:00
|
|
|
}
|
|
|
|
if hs.Listener != nil {
|
|
|
|
hs.log.Debug("Using provided listener")
|
|
|
|
}
|
2018-07-01 09:01:43 -05:00
|
|
|
hs.registerRoutes()
|
2021-08-25 08:11:22 -05:00
|
|
|
|
|
|
|
if err := hs.declareFixedRoles(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return hs, nil
|
2016-12-21 07:36:32 -06:00
|
|
|
}
|
|
|
|
|
2021-10-11 07:30:59 -05:00
|
|
|
func (hs *HTTPServer) AddMiddleware(middleware web.Handler) {
|
2020-07-23 02:54:07 -05:00
|
|
|
hs.middlewares = append(hs.middlewares, middleware)
|
|
|
|
}
|
|
|
|
|
2022-01-24 07:41:18 -06:00
|
|
|
func (hs *HTTPServer) AddNamedMiddleware(middleware routing.RegisterNamedMiddleware) {
|
|
|
|
hs.namedMiddlewares = append(hs.namedMiddlewares, middleware)
|
|
|
|
}
|
|
|
|
|
2018-05-01 08:51:15 -05:00
|
|
|
func (hs *HTTPServer) Run(ctx context.Context) error {
|
2016-12-21 07:36:32 -06:00
|
|
|
hs.context = ctx
|
2018-07-02 01:35:50 -05:00
|
|
|
|
2018-07-01 09:01:43 -05:00
|
|
|
hs.applyRoutes()
|
2016-12-21 07:36:32 -06:00
|
|
|
|
2021-02-15 10:55:41 -06:00
|
|
|
// Remove any square brackets enclosing IPv6 addresses, a format we support for backwards compatibility
|
2021-03-10 05:41:29 -06:00
|
|
|
host := strings.TrimSuffix(strings.TrimPrefix(hs.Cfg.HTTPAddr, "["), "]")
|
2019-11-27 05:07:21 -06:00
|
|
|
hs.httpSrv = &http.Server{
|
2021-03-19 05:21:52 -05:00
|
|
|
Addr: net.JoinHostPort(host, hs.Cfg.HTTPPort),
|
2021-10-11 07:30:59 -05:00
|
|
|
Handler: hs.web,
|
2021-03-19 05:21:52 -05:00
|
|
|
ReadTimeout: hs.Cfg.ReadTimeout,
|
2019-10-22 06:07:43 -05:00
|
|
|
}
|
2020-12-11 04:44:44 -06:00
|
|
|
switch hs.Cfg.Protocol {
|
2020-10-02 08:45:45 -05:00
|
|
|
case setting.HTTP2Scheme:
|
2019-11-27 05:07:21 -06:00
|
|
|
if err := hs.configureHttp2(); err != nil {
|
|
|
|
return err
|
2019-08-16 10:06:54 -05:00
|
|
|
}
|
2020-10-02 08:45:45 -05:00
|
|
|
case setting.HTTPSScheme:
|
2019-11-27 05:07:21 -06:00
|
|
|
if err := hs.configureHttps(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-12-01 02:53:27 -06:00
|
|
|
default:
|
2019-11-27 05:07:21 -06:00
|
|
|
}
|
|
|
|
|
2020-08-21 03:41:10 -05:00
|
|
|
listener, err := hs.getListener()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2019-11-27 05:07:21 -06:00
|
|
|
}
|
2018-03-22 08:14:44 -05:00
|
|
|
|
2019-11-27 05:07:21 -06:00
|
|
|
hs.log.Info("HTTP Server Listen", "address", listener.Addr().String(), "protocol",
|
2020-12-11 04:44:44 -06:00
|
|
|
hs.Cfg.Protocol, "subUrl", hs.Cfg.AppSubURL, "socket", hs.Cfg.SocketPath)
|
2019-11-27 05:07:21 -06:00
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(1)
|
|
|
|
|
|
|
|
// handle http shutdown on server context done
|
|
|
|
go func() {
|
2019-11-27 06:42:15 -06:00
|
|
|
defer wg.Done()
|
|
|
|
|
2019-11-27 05:07:21 -06:00
|
|
|
<-ctx.Done()
|
|
|
|
if err := hs.httpSrv.Shutdown(context.Background()); err != nil {
|
|
|
|
hs.log.Error("Failed to shutdown server", "error", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2020-12-11 04:44:44 -06:00
|
|
|
switch hs.Cfg.Protocol {
|
2020-10-02 08:45:45 -05:00
|
|
|
case setting.HTTPScheme, setting.SocketScheme:
|
2019-11-27 05:07:21 -06:00
|
|
|
if err := hs.httpSrv.Serve(listener); err != nil {
|
2020-11-19 06:34:28 -06:00
|
|
|
if errors.Is(err, http.ErrServerClosed) {
|
2019-11-27 05:07:21 -06:00
|
|
|
hs.log.Debug("server was shutdown gracefully")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
2020-10-02 08:45:45 -05:00
|
|
|
case setting.HTTP2Scheme, setting.HTTPSScheme:
|
2021-03-10 05:41:29 -06:00
|
|
|
if err := hs.httpSrv.ServeTLS(listener, hs.Cfg.CertFile, hs.Cfg.KeyFile); err != nil {
|
2020-11-19 06:34:28 -06:00
|
|
|
if errors.Is(err, http.ErrServerClosed) {
|
2019-11-27 05:07:21 -06:00
|
|
|
hs.log.Debug("server was shutdown gracefully")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
2017-04-27 01:54:21 -05:00
|
|
|
}
|
2016-12-21 07:36:32 -06:00
|
|
|
default:
|
2020-12-11 04:44:44 -06:00
|
|
|
panic(fmt.Sprintf("Unhandled protocol %q", hs.Cfg.Protocol))
|
2016-12-21 07:36:32 -06:00
|
|
|
}
|
|
|
|
|
2019-11-27 05:07:21 -06:00
|
|
|
wg.Wait()
|
|
|
|
|
|
|
|
return nil
|
2016-12-21 07:36:32 -06:00
|
|
|
}
|
|
|
|
|
2020-08-21 03:41:10 -05:00
|
|
|
func (hs *HTTPServer) getListener() (net.Listener, error) {
|
|
|
|
if hs.Listener != nil {
|
|
|
|
return hs.Listener, nil
|
|
|
|
}
|
|
|
|
|
2020-12-11 04:44:44 -06:00
|
|
|
switch hs.Cfg.Protocol {
|
2020-10-02 08:45:45 -05:00
|
|
|
case setting.HTTPScheme, setting.HTTPSScheme, setting.HTTP2Scheme:
|
2020-08-21 03:41:10 -05:00
|
|
|
listener, err := net.Listen("tcp", hs.httpSrv.Addr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errutil.Wrapf(err, "failed to open listener on address %s", hs.httpSrv.Addr)
|
|
|
|
}
|
|
|
|
return listener, nil
|
2020-10-02 08:45:45 -05:00
|
|
|
case setting.SocketScheme:
|
2020-12-11 04:44:44 -06:00
|
|
|
listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: hs.Cfg.SocketPath, Net: "unix"})
|
2020-08-21 03:41:10 -05:00
|
|
|
if err != nil {
|
2020-12-11 04:44:44 -06:00
|
|
|
return nil, errutil.Wrapf(err, "failed to open listener for socket %s", hs.Cfg.SocketPath)
|
2020-08-21 03:41:10 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Make socket writable by group
|
2020-12-10 04:53:21 -06:00
|
|
|
// nolint:gosec
|
2020-12-11 04:44:44 -06:00
|
|
|
if err := os.Chmod(hs.Cfg.SocketPath, 0660); err != nil {
|
2020-08-21 03:41:10 -05:00
|
|
|
return nil, errutil.Wrapf(err, "failed to change socket permissions")
|
|
|
|
}
|
|
|
|
|
|
|
|
return listener, nil
|
|
|
|
default:
|
2020-12-11 04:44:44 -06:00
|
|
|
hs.log.Error("Invalid protocol", "protocol", hs.Cfg.Protocol)
|
|
|
|
return nil, fmt.Errorf("invalid protocol %q", hs.Cfg.Protocol)
|
2020-08-21 03:41:10 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-27 05:07:21 -06:00
|
|
|
func (hs *HTTPServer) configureHttps() error {
|
2021-03-10 05:41:29 -06:00
|
|
|
if hs.Cfg.CertFile == "" {
|
2016-12-21 07:36:32 -06:00
|
|
|
return fmt.Errorf("cert_file cannot be empty when using HTTPS")
|
|
|
|
}
|
|
|
|
|
2021-03-10 05:41:29 -06:00
|
|
|
if hs.Cfg.KeyFile == "" {
|
2016-12-21 07:36:32 -06:00
|
|
|
return fmt.Errorf("cert_key cannot be empty when using HTTPS")
|
|
|
|
}
|
|
|
|
|
2021-03-10 05:41:29 -06:00
|
|
|
if _, err := os.Stat(hs.Cfg.CertFile); os.IsNotExist(err) {
|
|
|
|
return fmt.Errorf(`cannot find SSL cert_file at %q`, hs.Cfg.CertFile)
|
2016-12-21 07:36:32 -06:00
|
|
|
}
|
|
|
|
|
2021-03-10 05:41:29 -06:00
|
|
|
if _, err := os.Stat(hs.Cfg.KeyFile); os.IsNotExist(err) {
|
|
|
|
return fmt.Errorf(`cannot find SSL key_file at %q`, hs.Cfg.KeyFile)
|
2016-12-21 07:36:32 -06:00
|
|
|
}
|
|
|
|
|
2017-02-15 07:29:20 -06:00
|
|
|
tlsCfg := &tls.Config{
|
|
|
|
MinVersion: tls.VersionTLS12,
|
|
|
|
PreferServerCipherSuites: true,
|
|
|
|
CipherSuites: []uint16{
|
2020-02-18 11:58:36 -06:00
|
|
|
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
|
|
|
|
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
|
|
|
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
|
|
|
|
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
2017-02-15 07:29:20 -06:00
|
|
|
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
|
2020-02-18 11:58:36 -06:00
|
|
|
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
|
2017-02-15 07:29:20 -06:00
|
|
|
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
|
2020-02-18 11:58:36 -06:00
|
|
|
tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
|
|
|
|
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
|
|
|
|
tls.TLS_RSA_WITH_AES_128_CBC_SHA,
|
|
|
|
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
|
2017-02-15 07:29:20 -06:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2017-06-17 16:10:12 -05:00
|
|
|
hs.httpSrv.TLSConfig = tlsCfg
|
2018-04-16 13:22:12 -05:00
|
|
|
hs.httpSrv.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
|
2017-06-17 16:10:12 -05:00
|
|
|
|
2019-11-27 05:07:21 -06:00
|
|
|
return nil
|
2016-12-21 07:36:32 -06:00
|
|
|
}
|
|
|
|
|
2019-11-27 05:07:21 -06:00
|
|
|
func (hs *HTTPServer) configureHttp2() error {
|
2021-03-10 05:41:29 -06:00
|
|
|
if hs.Cfg.CertFile == "" {
|
2019-08-16 10:06:54 -05:00
|
|
|
return fmt.Errorf("cert_file cannot be empty when using HTTP2")
|
|
|
|
}
|
|
|
|
|
2021-03-10 05:41:29 -06:00
|
|
|
if hs.Cfg.KeyFile == "" {
|
2019-08-16 10:06:54 -05:00
|
|
|
return fmt.Errorf("cert_key cannot be empty when using HTTP2")
|
|
|
|
}
|
|
|
|
|
2021-03-10 05:41:29 -06:00
|
|
|
if _, err := os.Stat(hs.Cfg.CertFile); os.IsNotExist(err) {
|
|
|
|
return fmt.Errorf(`cannot find SSL cert_file at %q`, hs.Cfg.CertFile)
|
2019-08-16 10:06:54 -05:00
|
|
|
}
|
|
|
|
|
2021-03-10 05:41:29 -06:00
|
|
|
if _, err := os.Stat(hs.Cfg.KeyFile); os.IsNotExist(err) {
|
|
|
|
return fmt.Errorf(`cannot find SSL key_file at %q`, hs.Cfg.KeyFile)
|
2019-08-16 10:06:54 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
tlsCfg := &tls.Config{
|
|
|
|
MinVersion: tls.VersionTLS12,
|
2020-11-25 07:56:34 -06:00
|
|
|
PreferServerCipherSuites: true,
|
2019-08-16 10:06:54 -05:00
|
|
|
CipherSuites: []uint16{
|
|
|
|
tls.TLS_CHACHA20_POLY1305_SHA256,
|
|
|
|
tls.TLS_AES_128_GCM_SHA256,
|
|
|
|
tls.TLS_AES_256_GCM_SHA384,
|
|
|
|
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
|
|
|
|
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
2020-02-18 11:58:36 -06:00
|
|
|
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
|
2019-08-16 10:06:54 -05:00
|
|
|
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
2020-02-18 11:58:36 -06:00
|
|
|
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
|
|
|
|
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
|
2019-08-16 10:06:54 -05:00
|
|
|
},
|
|
|
|
NextProtos: []string{"h2", "http/1.1"},
|
|
|
|
}
|
|
|
|
|
|
|
|
hs.httpSrv.TLSConfig = tlsCfg
|
|
|
|
|
2019-11-27 05:07:21 -06:00
|
|
|
return nil
|
2019-08-16 10:06:54 -05:00
|
|
|
}
|
|
|
|
|
2018-07-02 01:35:50 -05:00
|
|
|
func (hs *HTTPServer) applyRoutes() {
|
|
|
|
// start with middlewares & static routes
|
|
|
|
hs.addMiddlewaresAndStaticRoutes()
|
|
|
|
// then add view routes & api routes
|
2022-01-24 07:41:18 -06:00
|
|
|
hs.RouteRegister.Register(hs.web, hs.namedMiddlewares...)
|
2018-07-02 01:35:50 -05:00
|
|
|
// then custom app proxy routes
|
2021-10-11 07:30:59 -05:00
|
|
|
hs.initAppPluginRoutes(hs.web)
|
2018-07-02 01:35:50 -05:00
|
|
|
// lastly not found route
|
2021-10-11 07:30:59 -05:00
|
|
|
hs.web.NotFound(middleware.ReqSignedIn, hs.NotFoundHandler)
|
2018-07-02 01:35:50 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (hs *HTTPServer) addMiddlewaresAndStaticRoutes() {
|
2021-10-11 07:30:59 -05:00
|
|
|
m := hs.web
|
2018-07-02 01:35:50 -05:00
|
|
|
|
2022-01-20 04:10:12 -06:00
|
|
|
m.Use(middleware.RequestTracing(hs.tracer))
|
2022-02-02 11:48:46 -06:00
|
|
|
m.Use(middleware.RequestMetrics(hs.Features))
|
2021-04-20 08:22:22 -05:00
|
|
|
|
2020-12-11 04:44:44 -06:00
|
|
|
m.Use(middleware.Logger(hs.Cfg))
|
2016-12-21 07:36:32 -06:00
|
|
|
|
2021-03-10 05:41:29 -06:00
|
|
|
if hs.Cfg.EnableGzip {
|
2021-08-10 06:29:46 -05:00
|
|
|
m.UseMiddleware(middleware.Gziper())
|
2016-12-21 07:36:32 -06:00
|
|
|
}
|
|
|
|
|
2020-12-11 04:44:44 -06:00
|
|
|
m.Use(middleware.Recovery(hs.Cfg))
|
2022-02-09 06:44:38 -06:00
|
|
|
m.UseMiddleware(middleware.CSRF(hs.Cfg.LoginCookieName))
|
2017-11-15 06:51:15 -06:00
|
|
|
|
2021-03-10 05:41:29 -06:00
|
|
|
hs.mapStatic(m, hs.Cfg.StaticRootPath, "build", "public/build")
|
2022-02-08 06:38:43 -06:00
|
|
|
hs.mapStatic(m, hs.Cfg.StaticRootPath, "", "public", "/public/views/swagger.html")
|
2021-03-10 05:41:29 -06:00
|
|
|
hs.mapStatic(m, hs.Cfg.StaticRootPath, "robots.txt", "robots.txt")
|
2016-12-21 07:36:32 -06:00
|
|
|
|
2021-03-10 05:41:29 -06:00
|
|
|
if hs.Cfg.ImageUploadProvider == "local" {
|
2018-05-24 08:26:27 -05:00
|
|
|
hs.mapStatic(m, hs.Cfg.ImagesDir, "", "/public/img/attachments")
|
2017-12-30 16:01:51 -06:00
|
|
|
}
|
|
|
|
|
2020-12-11 04:44:44 -06:00
|
|
|
m.Use(middleware.AddDefaultResponseHeaders(hs.Cfg))
|
2019-05-06 02:22:59 -05:00
|
|
|
|
2021-03-10 05:41:29 -06:00
|
|
|
if hs.Cfg.ServeFromSubPath && hs.Cfg.AppSubURL != "" {
|
|
|
|
m.SetURLPrefix(hs.Cfg.AppSubURL)
|
2019-05-27 10:47:29 -05:00
|
|
|
}
|
|
|
|
|
2021-10-11 07:30:59 -05:00
|
|
|
m.UseMiddleware(web.Renderer(filepath.Join(hs.Cfg.StaticRootPath, "views"), "[[", "]]"))
|
2016-12-21 07:36:32 -06:00
|
|
|
|
2020-10-02 00:14:26 -05:00
|
|
|
// These endpoints are used for monitoring the Grafana instance
|
2020-10-21 04:06:19 -05:00
|
|
|
// and should not be redirected or rejected.
|
2020-10-02 00:14:26 -05:00
|
|
|
m.Use(hs.healthzHandler)
|
|
|
|
m.Use(hs.apiHealthHandler)
|
2017-09-06 15:24:10 -05:00
|
|
|
m.Use(hs.metricsEndpoint)
|
2020-10-02 00:14:26 -05:00
|
|
|
|
2020-12-11 04:44:44 -06:00
|
|
|
m.Use(hs.ContextHandler.Middleware)
|
2020-12-15 12:09:04 -06:00
|
|
|
m.Use(middleware.OrgRedirect(hs.Cfg))
|
2021-12-14 09:05:59 -06:00
|
|
|
m.Use(acmiddleware.LoadPermissionsMiddleware(hs.AccessControl))
|
2016-12-21 07:36:32 -06:00
|
|
|
|
|
|
|
// needs to be after context handler
|
2021-03-10 05:41:29 -06:00
|
|
|
if hs.Cfg.EnforceDomain {
|
2020-12-15 12:09:04 -06:00
|
|
|
m.Use(middleware.ValidateHostHeader(hs.Cfg))
|
2016-12-21 07:36:32 -06:00
|
|
|
}
|
|
|
|
|
2021-01-12 00:42:32 -06:00
|
|
|
m.Use(middleware.HandleNoCacheHeader)
|
2021-08-10 02:03:22 -05:00
|
|
|
m.UseMiddleware(middleware.AddCSPHeader(hs.Cfg, hs.log))
|
2020-07-23 02:54:07 -05:00
|
|
|
|
|
|
|
for _, mw := range hs.middlewares {
|
|
|
|
m.Use(mw)
|
|
|
|
}
|
2016-12-21 07:36:32 -06:00
|
|
|
}
|
|
|
|
|
2021-10-11 07:30:59 -05:00
|
|
|
func (hs *HTTPServer) metricsEndpoint(ctx *web.Context) {
|
2018-09-13 07:36:16 -05:00
|
|
|
if !hs.Cfg.MetricsEndpointEnabled {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-06-12 00:27:47 -05:00
|
|
|
if ctx.Req.Method != http.MethodGet || ctx.Req.URL.Path != "/metrics" {
|
2017-09-06 15:24:10 -05:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-11-19 12:15:18 -06:00
|
|
|
if hs.metricsEndpointBasicAuthEnabled() && !BasicAuthenticatedRequest(ctx.Req, hs.Cfg.MetricsEndpointBasicAuthUsername, hs.Cfg.MetricsEndpointBasicAuthPassword) {
|
2018-11-14 16:37:32 -06:00
|
|
|
ctx.Resp.WriteHeader(http.StatusUnauthorized)
|
|
|
|
return
|
2018-11-14 14:42:47 -06:00
|
|
|
}
|
|
|
|
|
2019-07-15 00:33:48 -05:00
|
|
|
promhttp.
|
2020-12-01 08:04:59 -06:00
|
|
|
HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{EnableOpenMetrics: true}).
|
2021-09-01 04:18:30 -05:00
|
|
|
ServeHTTP(ctx.Resp, ctx.Req)
|
2017-09-06 15:24:10 -05:00
|
|
|
}
|
|
|
|
|
2020-09-18 06:03:18 -05:00
|
|
|
// healthzHandler always return 200 - Ok if Grafana's web server is running
|
2021-10-11 07:30:59 -05:00
|
|
|
func (hs *HTTPServer) healthzHandler(ctx *web.Context) {
|
2020-10-02 00:14:26 -05:00
|
|
|
notHeadOrGet := ctx.Req.Method != http.MethodGet && ctx.Req.Method != http.MethodHead
|
|
|
|
if notHeadOrGet || ctx.Req.URL.Path != "/healthz" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-08-10 06:29:46 -05:00
|
|
|
ctx.Resp.WriteHeader(200)
|
2020-09-18 06:03:18 -05:00
|
|
|
_, err := ctx.Resp.Write([]byte("Ok"))
|
|
|
|
if err != nil {
|
|
|
|
hs.log.Error("could not write to response", "err", err)
|
2017-04-25 10:17:45 -05:00
|
|
|
}
|
2020-09-18 06:03:18 -05:00
|
|
|
}
|
2017-04-25 10:17:45 -05:00
|
|
|
|
2020-09-18 06:03:18 -05:00
|
|
|
// apiHealthHandler will return ok if Grafana's web server is running and it
|
2020-10-21 04:06:19 -05:00
|
|
|
// can access the database. If the database cannot be accessed it will return
|
2020-09-18 06:03:18 -05:00
|
|
|
// http status code 503.
|
2021-10-11 07:30:59 -05:00
|
|
|
func (hs *HTTPServer) apiHealthHandler(ctx *web.Context) {
|
2020-10-02 00:14:26 -05:00
|
|
|
notHeadOrGet := ctx.Req.Method != http.MethodGet && ctx.Req.Method != http.MethodHead
|
|
|
|
if notHeadOrGet || ctx.Req.URL.Path != "/api/health" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-04-25 10:17:45 -05:00
|
|
|
data := simplejson.New()
|
2017-04-25 10:23:38 -05:00
|
|
|
data.Set("database", "ok")
|
2020-06-17 00:39:50 -05:00
|
|
|
if !hs.Cfg.AnonymousHideVersion {
|
2021-03-10 05:41:29 -06:00
|
|
|
data.Set("version", hs.Cfg.BuildVersion)
|
|
|
|
data.Set("commit", hs.Cfg.BuildCommit)
|
2020-06-17 00:39:50 -05:00
|
|
|
}
|
2017-04-25 10:17:45 -05:00
|
|
|
|
2021-10-11 07:35:03 -05:00
|
|
|
if !hs.databaseHealthy(ctx.Req.Context()) {
|
2017-04-25 10:24:36 -05:00
|
|
|
data.Set("database", "failing")
|
2017-05-10 08:23:59 -05:00
|
|
|
ctx.Resp.Header().Set("Content-Type", "application/json; charset=UTF-8")
|
|
|
|
ctx.Resp.WriteHeader(503)
|
|
|
|
} else {
|
|
|
|
ctx.Resp.Header().Set("Content-Type", "application/json; charset=UTF-8")
|
|
|
|
ctx.Resp.WriteHeader(200)
|
2017-04-25 10:17:45 -05:00
|
|
|
}
|
|
|
|
|
2020-08-18 07:58:08 -05:00
|
|
|
dataBytes, err := data.EncodePretty()
|
|
|
|
if err != nil {
|
|
|
|
hs.log.Error("Failed to encode data", "err", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-10-08 11:57:53 -05:00
|
|
|
if _, err := ctx.Resp.Write(dataBytes); err != nil {
|
|
|
|
hs.log.Error("Failed to write to response", "err", err)
|
|
|
|
}
|
2017-04-25 10:17:45 -05:00
|
|
|
}
|
|
|
|
|
2022-02-08 06:38:43 -06:00
|
|
|
func (hs *HTTPServer) mapStatic(m *web.Mux, rootDir string, dir string, prefix string, exclude ...string) {
|
2021-10-11 07:30:59 -05:00
|
|
|
headers := func(c *web.Context) {
|
2016-12-21 07:36:32 -06:00
|
|
|
c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
|
|
|
|
}
|
|
|
|
|
2018-05-08 06:54:00 -05:00
|
|
|
if prefix == "public/build" {
|
2021-10-11 07:30:59 -05:00
|
|
|
headers = func(c *web.Context) {
|
2018-05-08 06:54:00 -05:00
|
|
|
c.Resp.Header().Set("Cache-Control", "public, max-age=31536000")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-11 04:44:44 -06:00
|
|
|
if hs.Cfg.Env == setting.Dev {
|
2021-10-11 07:30:59 -05:00
|
|
|
headers = func(c *web.Context) {
|
2016-12-21 07:36:32 -06:00
|
|
|
c.Resp.Header().Set("Cache-Control", "max-age=0, must-revalidate, no-cache")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
m.Use(httpstatic.Static(
|
|
|
|
path.Join(rootDir, dir),
|
|
|
|
httpstatic.StaticOptions{
|
|
|
|
SkipLogging: true,
|
|
|
|
Prefix: prefix,
|
|
|
|
AddHeaders: headers,
|
2022-02-08 06:38:43 -06:00
|
|
|
Exclude: exclude,
|
2016-12-21 07:36:32 -06:00
|
|
|
},
|
|
|
|
))
|
|
|
|
}
|
2018-11-19 12:15:18 -06:00
|
|
|
|
|
|
|
func (hs *HTTPServer) metricsEndpointBasicAuthEnabled() bool {
|
|
|
|
return hs.Cfg.MetricsEndpointBasicAuthUsername != "" && hs.Cfg.MetricsEndpointBasicAuthPassword != ""
|
|
|
|
}
|