Files
grafana/pkg/api/http_server.go
T

799 lines
31 KiB
Go
Raw Normal View History

2016-12-21 14:36:32 +01:00
package api
import (
"context"
"crypto/tls"
2020-11-19 13:34:28 +01:00
"errors"
2016-12-21 14:36:32 +01:00
"fmt"
"net"
2016-12-21 14:36:32 +01:00
"net/http"
"os"
"path"
"path/filepath"
"strings"
"time"
2016-12-21 14:36:32 +01:00
"github.com/grafana/dskit/services"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/grafana/grafana/pkg/api/avatar"
2019-01-16 14:53:59 +01:00
"github.com/grafana/grafana/pkg/api/routing"
2016-12-21 14:36:32 +01:00
httpstatic "github.com/grafana/grafana/pkg/api/static"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/db"
"github.com/grafana/grafana/pkg/infra/kvstore"
2019-06-13 10:55:38 +02:00
"github.com/grafana/grafana/pkg/infra/localcache"
2019-05-13 14:45:54 +08:00
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/infra/remotecache"
"github.com/grafana/grafana/pkg/infra/tracing"
loginpkg "github.com/grafana/grafana/pkg/login"
"github.com/grafana/grafana/pkg/login/social"
2016-12-21 14:36:32 +01:00
"github.com/grafana/grafana/pkg/middleware"
"github.com/grafana/grafana/pkg/middleware/csrf"
"github.com/grafana/grafana/pkg/middleware/loggermw"
"github.com/grafana/grafana/pkg/modules"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/plugins/pluginscdn"
"github.com/grafana/grafana/pkg/registry/corekind"
"github.com/grafana/grafana/pkg/services/accesscontrol"
"github.com/grafana/grafana/pkg/services/alerting"
"github.com/grafana/grafana/pkg/services/annotations"
2022-08-02 16:55:19 +02:00
"github.com/grafana/grafana/pkg/services/apikey"
"github.com/grafana/grafana/pkg/services/auth"
"github.com/grafana/grafana/pkg/services/authn"
"github.com/grafana/grafana/pkg/services/cleanup"
"github.com/grafana/grafana/pkg/services/contexthandler"
"github.com/grafana/grafana/pkg/services/correlations"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/dashboardsnapshots"
dashver "github.com/grafana/grafana/pkg/services/dashboardversion"
"github.com/grafana/grafana/pkg/services/datasourceproxy"
2018-10-26 10:40:33 +02:00
"github.com/grafana/grafana/pkg/services/datasources"
"github.com/grafana/grafana/pkg/services/datasources/permissions"
"github.com/grafana/grafana/pkg/services/encryption"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/folder"
"github.com/grafana/grafana/pkg/services/hooks"
"github.com/grafana/grafana/pkg/services/libraryelements"
"github.com/grafana/grafana/pkg/services/librarypanels"
"github.com/grafana/grafana/pkg/services/licensing"
"github.com/grafana/grafana/pkg/services/live"
2021-04-26 13:17:49 +03:00
"github.com/grafana/grafana/pkg/services/live/pushhttp"
2019-06-13 17:47:52 +03:00
"github.com/grafana/grafana/pkg/services/login"
loginAttempt "github.com/grafana/grafana/pkg/services/loginattempt"
"github.com/grafana/grafana/pkg/services/navtree"
"github.com/grafana/grafana/pkg/services/ngalert"
2022-02-03 04:33:46 -05:00
"github.com/grafana/grafana/pkg/services/notifications"
"github.com/grafana/grafana/pkg/services/oauthtoken"
"github.com/grafana/grafana/pkg/services/org"
2022-07-18 12:26:35 +03:00
"github.com/grafana/grafana/pkg/services/playlist"
"github.com/grafana/grafana/pkg/services/plugindashboards"
"github.com/grafana/grafana/pkg/services/pluginsintegration/plugincontext"
pluginSettings "github.com/grafana/grafana/pkg/services/pluginsintegration/pluginsettings"
2022-04-21 15:03:17 +02:00
pref "github.com/grafana/grafana/pkg/services/preference"
"github.com/grafana/grafana/pkg/services/provisioning"
publicdashboardsApi "github.com/grafana/grafana/pkg/services/publicdashboards/api"
"github.com/grafana/grafana/pkg/services/query"
"github.com/grafana/grafana/pkg/services/queryhistory"
"github.com/grafana/grafana/pkg/services/quota"
2018-05-24 15:26:27 +02:00
"github.com/grafana/grafana/pkg/services/rendering"
"github.com/grafana/grafana/pkg/services/search"
"github.com/grafana/grafana/pkg/services/searchV2"
"github.com/grafana/grafana/pkg/services/searchusers"
2021-11-04 18:47:21 +02:00
"github.com/grafana/grafana/pkg/services/secrets"
secretsKV "github.com/grafana/grafana/pkg/services/secrets/kvstore"
spm "github.com/grafana/grafana/pkg/services/secrets/kvstore/migrations"
"github.com/grafana/grafana/pkg/services/serviceaccounts"
"github.com/grafana/grafana/pkg/services/shorturls"
"github.com/grafana/grafana/pkg/services/sqlstore"
2022-05-19 14:32:10 +02:00
"github.com/grafana/grafana/pkg/services/star"
starApi "github.com/grafana/grafana/pkg/services/star/api"
"github.com/grafana/grafana/pkg/services/stats"
2022-03-17 10:19:23 -07:00
"github.com/grafana/grafana/pkg/services/store"
"github.com/grafana/grafana/pkg/services/store/entity/httpentitystore"
2022-09-21 14:04:01 +02:00
"github.com/grafana/grafana/pkg/services/tag"
"github.com/grafana/grafana/pkg/services/team"
2022-08-12 12:13:23 -04:00
tempUser "github.com/grafana/grafana/pkg/services/temp_user"
"github.com/grafana/grafana/pkg/services/updatechecker"
"github.com/grafana/grafana/pkg/services/user"
"github.com/grafana/grafana/pkg/services/validations"
2016-12-21 14:36:32 +01:00
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
"github.com/grafana/grafana/pkg/web"
2016-12-21 14:36:32 +01:00
)
2018-03-22 22:13:46 +01:00
type HTTPServer struct {
// services.NamedService is embedded so we can inherit AddListener, without
// implementing the service interface.
services.NamedService
log log.Logger
web *web.Mux
context context.Context
httpSrv *http.Server
middlewares []web.Handler
namedMiddlewares []routing.RegisterNamedMiddleware
2022-06-14 16:07:41 +02:00
bus bus.Bus
errs chan error
2017-02-06 09:40:07 +01:00
pluginContextProvider *plugincontext.Provider
2022-02-09 14:01:32 +01:00
RouteRegister routing.RouteRegister
RenderService rendering.Service
Cfg *setting.Cfg
Features *featuremgmt.FeatureManager
SettingsProvider setting.Provider
HooksService *hooks.HooksService
navTreeService navtree.Service
2022-02-09 14:01:32 +01:00
CacheService *localcache.CacheService
DataSourceCache datasources.CacheService
2022-11-18 09:56:06 +01:00
AuthTokenService auth.UserTokenService
QuotaService quota.Service
2022-02-09 14:01:32 +01:00
RemoteCacheService *remotecache.RemoteCache
ProvisioningService provisioning.ProvisioningService
Login login.Service
License licensing.Licensing
2022-02-09 14:01:32 +01:00
AccessControl accesscontrol.AccessControl
DataProxy *datasourceproxy.DataSourceProxyService
PluginRequestValidator validations.PluginRequestValidator
2022-02-09 14:01:32 +01:00
pluginClient plugins.Client
pluginStore plugins.Store
pluginInstaller plugins.Installer
pluginFileStore plugins.FileStore
pluginDashboardService plugindashboards.Service
2022-02-09 14:01:32 +01:00
pluginStaticRouteResolver plugins.StaticRouteResolver
pluginErrorResolver plugins.ErrorResolver
SearchService search.Service
ShortURLService shorturls.Service
QueryHistoryService queryhistory.Service
CorrelationsService correlations.Service
2022-02-09 14:01:32 +01:00
Live *live.GrafanaLive
LivePushGateway *pushhttp.Gateway
StorageService store.StorageService
httpEntityStore httpentitystore.HTTPEntityStore
SearchV2HTTPService searchV2.SearchHTTPService
2022-02-09 14:01:32 +01:00
ContextHandler *contexthandler.ContextHandler
LoggerMiddleware loggermw.Logger
SQLStore db.DB
2022-02-09 14:01:32 +01:00
AlertEngine *alerting.AlertEngine
AlertNG *ngalert.AlertNG
LibraryPanelService librarypanels.Service
LibraryElementService libraryelements.Service
SocialService social.Service
Listener net.Listener
EncryptionService encryption.Internal
SecretsService secrets.Service
secretsPluginManager plugins.SecretsPluginManager
secretsStore secretsKV.SecretsKVStore
secretsMigrator secrets.Migrator
secretsPluginMigrator spm.SecretMigrationProvider
DataSourcesService datasources.DataSourceService
2022-02-09 14:01:32 +01:00
cleanUpService *cleanup.CleanUpService
tracer tracing.Tracer
grafanaUpdateChecker *updatechecker.GrafanaService
pluginsUpdateChecker *updatechecker.PluginsService
searchUsersService searchusers.Service
queryDataService query.Service
2022-02-09 14:01:32 +01:00
serviceAccountsService serviceaccounts.Service
authInfoService login.AuthInfoService
authenticator loginpkg.Authenticator
teamPermissionsService accesscontrol.TeamPermissionsService
2022-02-09 14:01:32 +01:00
NotificationService *notifications.NotificationService
2022-07-06 12:42:39 -06:00
DashboardService dashboards.DashboardService
dashboardProvisioningService dashboards.DashboardProvisioningService
folderService folder.Service
DatasourcePermissionsService permissions.DatasourcePermissionsService
AlertNotificationService *alerting.AlertNotificationService
dashboardsnapshotsService dashboardsnapshots.Service
PluginSettings pluginSettings.Service
AvatarCacheServer *avatar.AvatarCacheServer
2022-04-21 15:03:17 +02:00
preferenceService pref.Service
Csrf csrf.Service
folderPermissionsService accesscontrol.FolderPermissionsService
dashboardPermissionsService accesscontrol.DashboardPermissionsService
dashboardVersionService dashver.Service
PublicDashboardsApi *publicdashboardsApi.Api
2022-05-19 14:32:10 +02:00
starService star.Service
Kinds *corekind.Base
2022-07-18 12:26:35 +03:00
playlistService playlist.Service
2022-08-02 16:55:19 +02:00
apiKeyService apikey.Service
kvStore kvstore.KVStore
pluginsCDNService *pluginscdn.Service
userService user.Service
tempUserService tempUser.Service
loginAttemptService loginAttempt.Service
orgService org.Service
teamService team.Service
accesscontrolService accesscontrol.Service
annotationsRepo annotations.Repository
tagService tag.Service
oauthTokenService oauthtoken.OAuthTokenService
statsService stats.Service
authnService authn.Service
starApi *starApi.API
}
type ServerOptions struct {
Listener net.Listener
2016-12-21 14:36:32 +01:00
}
2022-06-14 16:07:41 +02:00
func ProvideHTTPServer(opts ServerOptions, cfg *setting.Cfg, routeRegister routing.RouteRegister, bus bus.Bus,
renderService rendering.Service, licensing licensing.Licensing, hooksService *hooks.HooksService,
2021-11-29 14:21:54 +01:00
cacheService *localcache.CacheService, sqlStore *sqlstore.SQLStore, alertEngine *alerting.AlertEngine,
pluginRequestValidator validations.PluginRequestValidator, pluginStaticRouteResolver plugins.StaticRouteResolver,
pluginDashboardService plugindashboards.Service, pluginStore plugins.Store, pluginClient plugins.Client,
pluginErrorResolver plugins.ErrorResolver, pluginInstaller plugins.Installer, settingsProvider setting.Provider,
2022-11-18 09:56:06 +01:00
dataSourceCache datasources.CacheService, userTokenService auth.UserTokenService,
cleanUpService *cleanup.CleanUpService, shortURLService shorturls.Service, queryHistoryService queryhistory.Service, correlationsService correlations.Service, remoteCache *remotecache.RemoteCache, provisioningService provisioning.ProvisioningService,
loginService login.Service, authenticator loginpkg.Authenticator, accessControl accesscontrol.AccessControl,
dataSourceProxy *datasourceproxy.DataSourceProxyService, searchService *search.SearchService,
live *live.GrafanaLive, livePushGateway *pushhttp.Gateway, plugCtxProvider *plugincontext.Provider,
contextHandler *contexthandler.ContextHandler, loggerMiddleware loggermw.Logger, features *featuremgmt.FeatureManager,
alertNG *ngalert.AlertNG, libraryPanelService librarypanels.Service, libraryElementService libraryelements.Service,
quotaService quota.Service, socialService social.Service, tracer tracing.Tracer,
encryptionService encryption.Internal, grafanaUpdateChecker *updatechecker.GrafanaService,
pluginsUpdateChecker *updatechecker.PluginsService, searchUsersService searchusers.Service,
dataSourcesService datasources.DataSourceService, queryDataService query.Service, pluginFileStore plugins.FileStore,
serviceaccountsService serviceaccounts.Service,
authInfoService login.AuthInfoService, storageService store.StorageService, httpEntityStore httpentitystore.HTTPEntityStore,
notificationService *notifications.NotificationService, dashboardService dashboards.DashboardService,
dashboardProvisioningService dashboards.DashboardProvisioningService, folderService folder.Service,
datasourcePermissionsService permissions.DatasourcePermissionsService, alertNotificationService *alerting.AlertNotificationService,
2023-03-11 04:28:12 -08:00
dashboardsnapshotsService dashboardsnapshots.Service, pluginSettings pluginSettings.Service,
avatarCacheServer *avatar.AvatarCacheServer, preferenceService pref.Service,
teamsPermissionsService accesscontrol.TeamPermissionsService, folderPermissionsService accesscontrol.FolderPermissionsService,
dashboardPermissionsService accesscontrol.DashboardPermissionsService, dashboardVersionService dashver.Service,
starService star.Service, csrfService csrf.Service, basekinds *corekind.Base,
playlistService playlist.Service, apiKeyService apikey.Service, kvStore kvstore.KVStore,
secretsMigrator secrets.Migrator, secretsPluginManager plugins.SecretsPluginManager, secretsService secrets.Service,
secretsPluginMigrator spm.SecretMigrationProvider, secretsStore secretsKV.SecretsKVStore,
publicDashboardsApi *publicdashboardsApi.Api, userService user.Service, tempUserService tempUser.Service,
loginAttemptService loginAttempt.Service, orgService org.Service, teamService team.Service,
accesscontrolService accesscontrol.Service, navTreeService navtree.Service,
annotationRepo annotations.Repository, tagService tag.Service, searchv2HTTPService searchV2.SearchHTTPService, oauthTokenService oauthtoken.OAuthTokenService,
statsService stats.Service, authnService authn.Service, pluginsCDNService *pluginscdn.Service,
starApi *starApi.API,
) (*HTTPServer, error) {
web.Env = cfg.Env
m := web.New()
2018-05-01 15:51:15 +02:00
hs := &HTTPServer{
2022-02-09 14:01:32 +01:00
Cfg: cfg,
RouteRegister: routeRegister,
2022-06-14 16:07:41 +02:00
bus: bus,
2022-02-09 14:01:32 +01:00
RenderService: renderService,
License: licensing,
HooksService: hooksService,
CacheService: cacheService,
SQLStore: sqlStore,
AlertEngine: alertEngine,
PluginRequestValidator: pluginRequestValidator,
pluginInstaller: pluginInstaller,
2022-02-09 14:01:32 +01:00
pluginClient: pluginClient,
pluginStore: pluginStore,
pluginStaticRouteResolver: pluginStaticRouteResolver,
pluginDashboardService: pluginDashboardService,
2022-02-09 14:01:32 +01:00
pluginErrorResolver: pluginErrorResolver,
pluginFileStore: pluginFileStore,
2022-02-09 14:01:32 +01:00
grafanaUpdateChecker: grafanaUpdateChecker,
pluginsUpdateChecker: pluginsUpdateChecker,
SettingsProvider: settingsProvider,
DataSourceCache: dataSourceCache,
AuthTokenService: userTokenService,
cleanUpService: cleanUpService,
ShortURLService: shortURLService,
QueryHistoryService: queryHistoryService,
CorrelationsService: correlationsService,
2022-02-09 14:01:32 +01:00
Features: features,
2022-03-17 10:19:23 -07:00
StorageService: storageService,
2022-02-09 14:01:32 +01:00
RemoteCacheService: remoteCache,
ProvisioningService: provisioningService,
Login: loginService,
AccessControl: accessControl,
DataProxy: dataSourceProxy,
SearchV2HTTPService: searchv2HTTPService,
2022-02-09 14:01:32 +01:00
SearchService: searchService,
Live: live,
LivePushGateway: livePushGateway,
pluginContextProvider: plugCtxProvider,
2022-02-09 14:01:32 +01:00
ContextHandler: contextHandler,
LoggerMiddleware: loggerMiddleware,
2022-02-09 14:01:32 +01:00
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,
secretsPluginManager: secretsPluginManager,
secretsMigrator: secretsMigrator,
secretsPluginMigrator: secretsPluginMigrator,
secretsStore: secretsStore,
httpEntityStore: httpEntityStore,
2022-02-09 14:01:32 +01:00
DataSourcesService: dataSourcesService,
searchUsersService: searchUsersService,
queryDataService: queryDataService,
serviceAccountsService: serviceaccountsService,
authInfoService: authInfoService,
authenticator: authenticator,
2022-02-09 14:01:32 +01:00
NotificationService: notificationService,
2022-07-06 12:42:39 -06:00
DashboardService: dashboardService,
dashboardProvisioningService: dashboardProvisioningService,
folderService: folderService,
2022-02-09 14:01:32 +01:00
DatasourcePermissionsService: datasourcePermissionsService,
teamPermissionsService: teamsPermissionsService,
AlertNotificationService: alertNotificationService,
dashboardsnapshotsService: dashboardsnapshotsService,
PluginSettings: pluginSettings,
AvatarCacheServer: avatarCacheServer,
2022-04-21 15:03:17 +02:00
preferenceService: preferenceService,
Csrf: csrfService,
folderPermissionsService: folderPermissionsService,
dashboardPermissionsService: dashboardPermissionsService,
dashboardVersionService: dashboardVersionService,
2022-05-19 14:32:10 +02:00
starService: starService,
Kinds: basekinds,
2022-07-18 12:26:35 +03:00
playlistService: playlistService,
2022-08-02 16:55:19 +02:00
apiKeyService: apiKeyService,
kvStore: kvStore,
PublicDashboardsApi: publicDashboardsApi,
userService: userService,
2022-08-12 12:13:23 -04:00
tempUserService: tempUserService,
2022-08-17 02:34:23 -04:00
loginAttemptService: loginAttemptService,
orgService: orgService,
teamService: teamService,
navTreeService: navTreeService,
accesscontrolService: accesscontrolService,
annotationsRepo: annotationRepo,
2022-09-21 14:04:01 +02:00
tagService: tagService,
oauthTokenService: oauthTokenService,
statsService: statsService,
authnService: authnService,
pluginsCDNService: pluginsCDNService,
starApi: starApi,
errs: make(chan error),
}
if hs.Listener != nil {
hs.log.Debug("Using provided listener")
}
2018-07-01 16:01:43 +02:00
hs.registerRoutes()
// Register access control scope resolver for annotations
hs.AccessControl.RegisterScopeAttributeResolver(AnnotationTypeScopeResolver(hs.annotationsRepo))
if err := hs.declareFixedRoles(); err != nil {
return nil, err
}
hs.NamedService = services.NewBasicService(hs.start, hs.running, hs.stop).WithName(modules.HTTPServer)
return hs, nil
2016-12-21 14:36:32 +01:00
}
func (hs *HTTPServer) AddMiddleware(middleware web.Handler) {
hs.middlewares = append(hs.middlewares, middleware)
}
func (hs *HTTPServer) AddNamedMiddleware(middleware routing.RegisterNamedMiddleware) {
hs.namedMiddlewares = append(hs.namedMiddlewares, middleware)
}
func (hs *HTTPServer) start(ctx context.Context) error {
2016-12-21 14:36:32 +01:00
hs.context = ctx
2018-07-01 16:01:43 +02:00
hs.applyRoutes()
2016-12-21 14:36:32 +01:00
// Remove any square brackets enclosing IPv6 addresses, a format we support for backwards compatibility
host := strings.TrimSuffix(strings.TrimPrefix(hs.Cfg.HTTPAddr, "["), "]")
hs.httpSrv = &http.Server{
Addr: net.JoinHostPort(host, hs.Cfg.HTTPPort),
Handler: hs.web,
ReadTimeout: hs.Cfg.ReadTimeout,
}
switch hs.Cfg.Protocol {
case setting.HTTP2Scheme:
if err := hs.configureHttp2(); err != nil {
return err
2019-08-16 16:06:54 +01:00
}
case setting.HTTPSScheme:
if err := hs.configureHttps(); err != nil {
return err
}
2020-12-01 09:53:27 +01:00
default:
}
listener, err := hs.getListener()
if err != nil {
return err
}
2018-03-22 14:14:44 +01:00
hs.log.Info("HTTP Server Listen", "address", listener.Addr().String(), "protocol",
hs.Cfg.Protocol, "subUrl", hs.Cfg.AppSubURL, "socket", hs.Cfg.SocketPath)
switch hs.Cfg.Protocol {
case setting.HTTPScheme, setting.SocketScheme:
go func() {
if err := hs.httpSrv.Serve(listener); err != nil {
if errors.Is(err, http.ErrServerClosed) {
hs.log.Debug("server was shutdown gracefully")
close(hs.errs)
return
}
hs.errs <- err
}
}()
case setting.HTTP2Scheme, setting.HTTPSScheme:
go func() {
if err := hs.httpSrv.ServeTLS(listener, hs.Cfg.CertFile, hs.Cfg.KeyFile); err != nil {
if errors.Is(err, http.ErrServerClosed) {
hs.log.Debug("server was shutdown gracefully")
close(hs.errs)
return
}
hs.errs <- err
}
}()
2016-12-21 14:36:32 +01:00
default:
panic(fmt.Sprintf("Unhandled protocol %q", hs.Cfg.Protocol))
2016-12-21 14:36:32 +01:00
}
return nil
}
func (hs *HTTPServer) running(ctx context.Context) error {
select {
case err, ok := <-hs.errs:
if !ok {
return nil
}
return err
case <-ctx.Done():
}
return nil
2016-12-21 14:36:32 +01:00
}
func (hs *HTTPServer) stop(_ error) error {
// Create a context with a timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := hs.httpSrv.Shutdown(ctx); err != nil {
return fmt.Errorf("failed to shutdown server: %w", err)
}
return nil
}
func (hs *HTTPServer) getListener() (net.Listener, error) {
if hs.Listener != nil {
return hs.Listener, nil
}
switch hs.Cfg.Protocol {
case setting.HTTPScheme, setting.HTTPSScheme, setting.HTTP2Scheme:
listener, err := net.Listen("tcp", hs.httpSrv.Addr)
if err != nil {
2022-06-06 16:30:31 -04:00
return nil, fmt.Errorf("failed to open listener on address %s: %w", hs.httpSrv.Addr, err)
}
return listener, nil
case setting.SocketScheme:
listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: hs.Cfg.SocketPath, Net: "unix"})
if err != nil {
2022-06-06 16:30:31 -04:00
return nil, fmt.Errorf("failed to open listener for socket %s: %w", hs.Cfg.SocketPath, err)
}
// Make socket writable by group
// nolint:gosec
if err := os.Chmod(hs.Cfg.SocketPath, os.FileMode(hs.Cfg.SocketMode)); err != nil {
return nil, fmt.Errorf("failed to change socket mode %d: %w", hs.Cfg.SocketMode, err)
}
// golang.org/pkg/os does not have chgrp
// Changing the gid of a file without privileges requires that the target group is in the group of the process and that the process is the file owner
if err := os.Chown(hs.Cfg.SocketPath, -1, hs.Cfg.SocketGid); err != nil {
return nil, fmt.Errorf("failed to change socket group id %d: %w", hs.Cfg.SocketGid, err)
}
return listener, nil
default:
hs.log.Error("Invalid protocol", "protocol", hs.Cfg.Protocol)
return nil, fmt.Errorf("invalid protocol %q", hs.Cfg.Protocol)
}
}
func (hs *HTTPServer) configureHttps() error {
if hs.Cfg.CertFile == "" {
return errors.New("cert_file cannot be empty when using HTTPS")
2016-12-21 14:36:32 +01:00
}
if hs.Cfg.KeyFile == "" {
return errors.New("cert_key cannot be empty when using HTTPS")
2016-12-21 14:36:32 +01: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 14:36:32 +01: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 14:36:32 +01:00
}
minTlsVersion, err := util.TlsNameToVersion(hs.Cfg.MinTLSVersion)
if err != nil {
return err
}
tlsCiphers := hs.getDefaultCiphers(minTlsVersion, string(setting.HTTPSScheme))
if err != nil {
return err
}
hs.log.Info("HTTP Server TLS settings", "Min TLS Version", hs.Cfg.MinTLSVersion,
"configured ciphers", util.TlsCipherIdsToString(tlsCiphers))
tlsCfg := &tls.Config{
MinVersion: minTlsVersion,
CipherSuites: tlsCiphers,
}
2017-06-17 23:10:12 +02:00
hs.httpSrv.TLSConfig = tlsCfg
2018-04-16 20:22:12 +02:00
hs.httpSrv.TLSNextProto = make(map[string]func(*http.Server, *tls.Conn, http.Handler))
2017-06-17 23:10:12 +02:00
return nil
2016-12-21 14:36:32 +01:00
}
func (hs *HTTPServer) configureHttp2() error {
if hs.Cfg.CertFile == "" {
return errors.New("cert_file cannot be empty when using HTTP2")
2019-08-16 16:06:54 +01:00
}
if hs.Cfg.KeyFile == "" {
return errors.New("cert_key cannot be empty when using HTTP2")
2019-08-16 16:06:54 +01: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 16:06:54 +01: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 16:06:54 +01:00
}
minTlsVersion, err := util.TlsNameToVersion(hs.Cfg.MinTLSVersion)
if err != nil {
return err
}
tlsCiphers := hs.getDefaultCiphers(minTlsVersion, string(setting.HTTP2Scheme))
hs.log.Info("HTTP Server TLS settings", "Min TLS Version", hs.Cfg.MinTLSVersion,
"configured ciphers", util.TlsCipherIdsToString(tlsCiphers))
2019-08-16 16:06:54 +01:00
tlsCfg := &tls.Config{
MinVersion: minTlsVersion,
CipherSuites: tlsCiphers,
NextProtos: []string{"h2", "http/1.1"},
2019-08-16 16:06:54 +01:00
}
hs.httpSrv.TLSConfig = tlsCfg
return nil
2019-08-16 16:06:54 +01:00
}
func (hs *HTTPServer) applyRoutes() {
// start with middlewares & static routes
hs.addMiddlewaresAndStaticRoutes()
// then add view routes & api routes
hs.RouteRegister.Register(hs.web, hs.namedMiddlewares...)
// lastly not found route
hs.web.NotFound(middleware.ProvideRouteOperationName("notfound"), middleware.ReqSignedIn, hs.NotFoundHandler)
}
func (hs *HTTPServer) addMiddlewaresAndStaticRoutes() {
m := hs.web
m.Use(middleware.RequestTracing(hs.tracer))
m.Use(middleware.RequestMetrics(hs.Features))
m.UseMiddleware(hs.LoggerMiddleware.Middleware())
2016-12-21 14:36:32 +01:00
if hs.Cfg.EnableGzip {
m.UseMiddleware(middleware.Gziper())
2016-12-21 14:36:32 +01:00
}
2022-08-09 14:58:50 +02:00
m.UseMiddleware(middleware.Recovery(hs.Cfg))
m.UseMiddleware(hs.Csrf.Middleware())
hs.mapStatic(m, hs.Cfg.StaticRootPath, "build", "public/build")
hs.mapStatic(m, hs.Cfg.StaticRootPath, "", "public", "/public/views/swagger.html")
hs.mapStatic(m, hs.Cfg.StaticRootPath, "robots.txt", "robots.txt")
2016-12-21 14:36:32 +01:00
if hs.Cfg.ImageUploadProvider == "local" {
2018-05-24 15:26:27 +02:00
hs.mapStatic(m, hs.Cfg.ImagesDir, "", "/public/img/attachments")
}
if len(hs.Cfg.CustomResponseHeaders) > 0 {
m.Use(middleware.AddCustomResponseHeaders(hs.Cfg))
}
m.Use(middleware.AddDefaultResponseHeaders(hs.Cfg))
if hs.Cfg.ServeFromSubPath && hs.Cfg.AppSubURL != "" {
m.SetURLPrefix(hs.Cfg.AppSubURL)
m.UseMiddleware(middleware.SubPathRedirect(hs.Cfg))
}
m.UseMiddleware(web.Renderer(filepath.Join(hs.Cfg.StaticRootPath, "views"), "[[", "]]"))
2016-12-21 14:36:32 +01:00
// These endpoints are used for monitoring the Grafana instance
// and should not be redirected or rejected.
m.Use(hs.healthzHandler)
m.Use(hs.apiHealthHandler)
2017-09-06 22:24:10 +02:00
m.Use(hs.metricsEndpoint)
m.Use(hs.pluginMetricsEndpoint)
m.Use(hs.frontendLogEndpoints())
m.UseMiddleware(hs.ContextHandler.Middleware)
m.Use(middleware.OrgRedirect(hs.Cfg, hs.userService))
2023-06-07 08:57:41 +02:00
if !hs.Cfg.AuthBrokerEnabled {
m.Use(accesscontrol.LoadPermissionsMiddleware(hs.accesscontrolService))
}
2016-12-21 14:36:32 +01:00
// needs to be after context handler
if hs.Cfg.EnforceDomain {
2020-12-15 19:09:04 +01:00
m.Use(middleware.ValidateHostHeader(hs.Cfg))
2016-12-21 14:36:32 +01:00
}
m.Use(middleware.HandleNoCacheHeaders)
if hs.Cfg.CSPEnabled || hs.Cfg.CSPReportOnlyEnabled {
m.UseMiddleware(middleware.ContentSecurityPolicy(hs.Cfg, hs.log))
}
for _, mw := range hs.middlewares {
m.Use(mw)
}
2016-12-21 14:36:32 +01:00
}
func (hs *HTTPServer) metricsEndpoint(ctx *web.Context) {
if !hs.Cfg.MetricsEndpointEnabled {
return
}
2019-06-12 07:27:47 +02:00
if ctx.Req.Method != http.MethodGet || ctx.Req.URL.Path != "/metrics" {
2017-09-06 22:24:10 +02:00
return
}
if hs.metricsEndpointBasicAuthEnabled() && !BasicAuthenticatedRequest(ctx.Req, hs.Cfg.MetricsEndpointBasicAuthUsername, hs.Cfg.MetricsEndpointBasicAuthPassword) {
2018-11-14 17:37:32 -05:00
ctx.Resp.WriteHeader(http.StatusUnauthorized)
return
}
promhttp.
HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{EnableOpenMetrics: true}).
ServeHTTP(ctx.Resp, ctx.Req)
2017-09-06 22:24:10 +02:00
}
2020-09-18 13:03:18 +02:00
// healthzHandler always return 200 - Ok if Grafana's web server is running
func (hs *HTTPServer) healthzHandler(ctx *web.Context) {
notHeadOrGet := ctx.Req.Method != http.MethodGet && ctx.Req.Method != http.MethodHead
if notHeadOrGet || ctx.Req.URL.Path != "/healthz" {
return
}
ctx.Resp.WriteHeader(http.StatusOK)
if _, err := ctx.Resp.Write([]byte("Ok")); err != nil {
2020-09-18 13:03:18 +02:00
hs.log.Error("could not write to response", "err", err)
}
2020-09-18 13:03:18 +02:00
}
2020-09-18 13:03:18 +02:00
// apiHealthHandler will return ok if Grafana's web server is running and it
// can access the database. If the database cannot be accessed it will return
2020-09-18 13:03:18 +02:00
// http status code 503.
func (hs *HTTPServer) apiHealthHandler(ctx *web.Context) {
notHeadOrGet := ctx.Req.Method != http.MethodGet && ctx.Req.Method != http.MethodHead
if notHeadOrGet || ctx.Req.URL.Path != "/api/health" {
return
}
data := simplejson.New()
data.Set("database", "ok")
if !hs.Cfg.AnonymousHideVersion {
data.Set("version", hs.Cfg.BuildVersion)
data.Set("commit", hs.Cfg.BuildCommit)
}
if !hs.databaseHealthy(ctx.Req.Context()) {
data.Set("database", "failing")
ctx.Resp.Header().Set("Content-Type", "application/json; charset=UTF-8")
ctx.Resp.WriteHeader(http.StatusServiceUnavailable)
} else {
ctx.Resp.Header().Set("Content-Type", "application/json; charset=UTF-8")
ctx.Resp.WriteHeader(http.StatusOK)
}
2020-08-18 14:58:08 +02:00
dataBytes, err := data.EncodePretty()
if err != nil {
hs.log.Error("Failed to encode data", "err", err)
return
}
2019-10-08 18:57:53 +02:00
if _, err := ctx.Resp.Write(dataBytes); err != nil {
hs.log.Error("Failed to write to response", "err", err)
}
}
func (hs *HTTPServer) mapStatic(m *web.Mux, rootDir string, dir string, prefix string, exclude ...string) {
headers := func(c *web.Context) {
2016-12-21 14:36:32 +01:00
c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
}
if prefix == "public/build" {
headers = func(c *web.Context) {
c.Resp.Header().Set("Cache-Control", "public, max-age=31536000")
}
}
if hs.Cfg.Env == setting.Dev {
headers = func(c *web.Context) {
2016-12-21 14:36:32 +01: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,
Exclude: exclude,
2016-12-21 14:36:32 +01:00
},
))
}
func (hs *HTTPServer) metricsEndpointBasicAuthEnabled() bool {
return hs.Cfg.MetricsEndpointBasicAuthUsername != "" && hs.Cfg.MetricsEndpointBasicAuthPassword != ""
}
func (hs *HTTPServer) getDefaultCiphers(tlsVersion uint16, protocol string) []uint16 {
if tlsVersion != tls.VersionTLS12 {
return nil
}
if protocol == "https" {
return []uint16{
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,
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
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,
}
}
if protocol == "h2" {
return []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,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
}
}
return nil
}