From 7ed011745a544873f40f806f1803cb8a4998ba01 Mon Sep 17 00:00:00 2001 From: Chris Date: Thu, 26 Oct 2017 14:21:22 -0500 Subject: Remove more global refs / state (#7723) * remove more global refs / state * fix job enterprise initialization * fix api4 test compilation * saml api endpoints fix --- api/admin.go | 2 +- api/apitestlib.go | 9 ------- api/status_test.go | 1 - api/user.go | 2 +- api4/saml.go | 15 ++++++------ api4/user_test.go | 11 ++++----- app/admin.go | 8 +++--- app/app.go | 14 +++++++++-- app/authentication.go | 19 +++++--------- app/oauth.go | 2 +- app/oauth_test.go | 11 ++++----- app/plugins.go | 4 +-- app/saml.go | 68 +++++++++++++++++++++++---------------------------- app/server.go | 24 +++--------------- app/session.go | 26 +++++++++----------- app/session_test.go | 6 ++--- app/user.go | 2 +- app/user_test.go | 10 ++++---- jobs/server.go | 8 ++++++ jobs/workers.go | 21 +++++++++------- model/config.go | 2 ++ utils/config.go | 4 ++- web/web.go | 10 ++++---- 23 files changed, 129 insertions(+), 150 deletions(-) diff --git a/api/admin.go b/api/admin.go index ff5971734..1e343fdfa 100644 --- a/api/admin.go +++ b/api/admin.go @@ -400,7 +400,7 @@ func removeCertificate(c *Context, w http.ResponseWriter, r *http.Request) { } func samlCertificateStatus(c *Context, w http.ResponseWriter, r *http.Request) { - status := app.GetSamlCertificateStatus() + status := c.App.GetSamlCertificateStatus() statusMap := map[string]interface{}{} statusMap["IdpCertificateFile"] = status.IdpCertificateFile diff --git a/api/apitestlib.go b/api/apitestlib.go index 17e2a6623..266ca95fc 100644 --- a/api/apitestlib.go +++ b/api/apitestlib.go @@ -114,15 +114,6 @@ func Setup() *TestHelper { return setupTestHelper(false) } -func ReloadConfigForSetup() { - utils.LoadConfig("config.json") - utils.InitTranslations(utils.Cfg.LocalizationSettings) - *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 - *utils.Cfg.RateLimitSettings.Enable = false - utils.Cfg.EmailSettings.SendEmailNotifications = true - *utils.Cfg.TeamSettings.EnableOpenServer = true -} - func (me *TestHelper) InitBasic() *TestHelper { me.waitForConnectivity() diff --git a/api/status_test.go b/api/status_test.go index 19d422b16..6a0ba3937 100644 --- a/api/status_test.go +++ b/api/status_test.go @@ -205,7 +205,6 @@ func TestStatuses(t *testing.T) { } func TestGetStatusesByIds(t *testing.T) { - ReloadConfigForSetup() th := Setup().InitBasic() defer th.TearDown() diff --git a/api/user.go b/api/user.go index 82796a6a9..e6f3327ba 100644 --- a/api/user.go +++ b/api/user.go @@ -292,7 +292,7 @@ func getInitialLoad(c *Context, w http.ResponseWriter, r *http.Request) { il.TeamMembers = c.Session.TeamMembers } - if app.SessionCacheLength() == 0 { + if c.App.SessionCacheLength() == 0 { // Below is a special case when intializating a new server // Lets check to make sure the server is really empty diff --git a/api4/saml.go b/api4/saml.go index ba9ee9eec..b2f2b3eef 100644 --- a/api4/saml.go +++ b/api4/saml.go @@ -8,7 +8,6 @@ import ( "net/http" l4g "github.com/alecthomas/log4go" - "github.com/mattermost/mattermost-server/app" "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/utils" ) @@ -73,7 +72,7 @@ func addSamlPublicCertificate(c *Context, w http.ResponseWriter, r *http.Request return } - if err := app.AddSamlPublicCertificate(fileData); err != nil { + if err := c.App.AddSamlPublicCertificate(fileData); err != nil { c.Err = err return } @@ -92,7 +91,7 @@ func addSamlPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Reques return } - if err := app.AddSamlPrivateCertificate(fileData); err != nil { + if err := c.App.AddSamlPrivateCertificate(fileData); err != nil { c.Err = err return } @@ -111,7 +110,7 @@ func addSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request) { return } - if err := app.AddSamlIdpCertificate(fileData); err != nil { + if err := c.App.AddSamlIdpCertificate(fileData); err != nil { c.Err = err return } @@ -124,7 +123,7 @@ func removeSamlPublicCertificate(c *Context, w http.ResponseWriter, r *http.Requ return } - if err := app.RemoveSamlPublicCertificate(); err != nil { + if err := c.App.RemoveSamlPublicCertificate(); err != nil { c.Err = err return } @@ -138,7 +137,7 @@ func removeSamlPrivateCertificate(c *Context, w http.ResponseWriter, r *http.Req return } - if err := app.RemoveSamlPrivateCertificate(); err != nil { + if err := c.App.RemoveSamlPrivateCertificate(); err != nil { c.Err = err return } @@ -152,7 +151,7 @@ func removeSamlIdpCertificate(c *Context, w http.ResponseWriter, r *http.Request return } - if err := app.RemoveSamlIdpCertificate(); err != nil { + if err := c.App.RemoveSamlIdpCertificate(); err != nil { c.Err = err return } @@ -166,6 +165,6 @@ func getSamlCertificateStatus(c *Context, w http.ResponseWriter, r *http.Request return } - status := app.GetSamlCertificateStatus() + status := c.App.GetSamlCertificateStatus() w.Write([]byte(status.ToJson())) } diff --git a/api4/user_test.go b/api4/user_test.go index eee9aa8a2..5424a1ee2 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -10,7 +10,6 @@ import ( "testing" "time" - "github.com/mattermost/mattermost-server/app" "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/utils" "github.com/stretchr/testify/assert" @@ -961,7 +960,7 @@ func TestUpdateUser(t *testing.T) { session, _ := th.App.GetSession(Client.AuthToken) session.IsOAuth = true - app.AddSessionToCache(session) + th.App.AddSessionToCache(session) ruser.Id = user.Id ruser.Email = GenerateTestEmail() @@ -1045,7 +1044,7 @@ func TestPatchUser(t *testing.T) { session, _ := th.App.GetSession(Client.AuthToken) session.IsOAuth = true - app.AddSessionToCache(session) + th.App.AddSessionToCache(session) patch.Email = model.NewString(GenerateTestEmail()) _, resp = Client.PatchUser(user.Id, patch) @@ -1513,7 +1512,7 @@ func TestUpdateUserMfa(t *testing.T) { session, _ := th.App.GetSession(Client.AuthToken) session.IsOAuth = true - app.AddSessionToCache(session) + th.App.AddSessionToCache(session) _, resp := Client.UpdateUserMfa(th.BasicUser.Id, "12345", false) CheckForbiddenStatus(t, resp) @@ -1609,7 +1608,7 @@ func TestGenerateMfaSecret(t *testing.T) { session, _ := th.App.GetSession(Client.AuthToken) session.IsOAuth = true - app.AddSessionToCache(session) + th.App.AddSessionToCache(session) _, resp = Client.GenerateMfaSecret(th.BasicUser.Id) CheckForbiddenStatus(t, resp) @@ -2257,7 +2256,7 @@ func TestCreateUserAccessToken(t *testing.T) { session, _ := th.App.GetSession(Client.AuthToken) session.IsOAuth = true - app.AddSessionToCache(session) + th.App.AddSessionToCache(session) _, resp = Client.CreateUserAccessToken(th.BasicUser.Id, testDescription) CheckForbiddenStatus(t, resp) diff --git a/app/admin.go b/app/admin.go index fc792a3f0..a181fa251 100644 --- a/app/admin.go +++ b/app/admin.go @@ -114,7 +114,7 @@ func (a *App) InvalidateAllCaches() *model.AppError { func (a *App) InvalidateAllCachesSkipSend() { l4g.Info(utils.T("api.context.invalidate_all_caches")) - sessionCache.Purge() + a.sessionCache.Purge() ClearStatusCache() sqlstore.ClearChannelCaches() sqlstore.ClearUserCaches() @@ -133,7 +133,7 @@ func (a *App) GetConfig() *model.Config { func (a *App) ReloadConfig() { debug.FreeOSMemory() - utils.LoadConfig(utils.CfgFileName) + utils.LoadConfig(a.ConfigFileName()) // start/restart email batching job if necessary a.InitEmailBatching() @@ -157,8 +157,8 @@ func (a *App) SaveConfig(cfg *model.Config, sendConfigChangeClusterMessage bool) } utils.DisableConfigWatch() - utils.SaveConfig(utils.CfgFileName, cfg) - utils.LoadConfig(utils.CfgFileName) + utils.SaveConfig(a.ConfigFileName(), cfg) + utils.LoadConfig(a.ConfigFileName()) utils.EnableConfigWatch() if a.Metrics != nil { diff --git a/app/app.go b/app/app.go index c82520cd9..002a6a272 100644 --- a/app/app.go +++ b/app/app.go @@ -48,6 +48,8 @@ type App struct { Saml einterfaces.SamlInterface newStore func() store.Store + + sessionCache *utils.Cache } var appCount = 0 @@ -64,10 +66,10 @@ func New(options ...Option) *App { app := &App{ goroutineExitSignal: make(chan struct{}, 1), - Jobs: &jobs.JobServer{}, Srv: &Server{ Router: mux.NewRouter(), }, + sessionCache: utils.NewLru(model.SESSION_CACHE_SIZE), } app.initEnterprise() @@ -82,7 +84,7 @@ func New(options ...Option) *App { } app.Srv.Store = app.newStore() - app.Jobs.Store = app.Srv.Store + app.initJobs() app.Srv.Router.NotFoundHandler = http.HandlerFunc(app.Handle404) @@ -218,6 +220,10 @@ func (a *App) initEnterprise() { if dataRetentionInterface != nil { a.DataRetention = dataRetentionInterface(a) } +} + +func (a *App) initJobs() { + a.Jobs = jobs.NewJobServer(a.Config, a.Srv.Store) if jobsDataRetentionJobInterface != nil { a.Jobs.DataRetentionJob = jobsDataRetentionJobInterface(a) } @@ -240,6 +246,10 @@ func (a *App) UpdateConfig(f func(*model.Config)) { f(utils.Cfg) } +func (a *App) ConfigFileName() string { + return utils.CfgFileName +} + // Go creates a goroutine, but maintains a record of it to ensure that execution completes before // the app is destroyed. func (a *App) Go(f func()) { diff --git a/app/authentication.go b/app/authentication.go index 7aae48b97..809c2e6c7 100644 --- a/app/authentication.go +++ b/app/authentication.go @@ -25,7 +25,7 @@ func (a *App) CheckPasswordAndAllCriteria(user *model.User, password string, mfa // This to be used for places we check the users password when they are already logged in func (a *App) doubleCheckPassword(user *model.User, password string) *model.AppError { - if err := checkUserLoginAttempts(user); err != nil { + if err := checkUserLoginAttempts(user, *a.Config().ServiceSettings.MaximumLoginAttempts); err != nil { return err } @@ -83,15 +83,15 @@ func (a *App) CheckUserAdditionalAuthenticationCriteria(user *model.User, mfaTok return err } - if err := checkEmailVerified(user); err != nil { - return err + if !user.EmailVerified && a.Config().EmailSettings.RequireEmailVerification { + return model.NewAppError("Login", "api.user.login.not_verified.app_error", nil, "user_id="+user.Id, http.StatusUnauthorized) } if err := checkUserNotDisabled(user); err != nil { return err } - if err := checkUserLoginAttempts(user); err != nil { + if err := checkUserLoginAttempts(user, *a.Config().ServiceSettings.MaximumLoginAttempts); err != nil { return err } @@ -116,21 +116,14 @@ func (a *App) CheckUserMfa(user *model.User, token string) *model.AppError { return nil } -func checkUserLoginAttempts(user *model.User) *model.AppError { - if user.FailedAttempts >= *utils.Cfg.ServiceSettings.MaximumLoginAttempts { +func checkUserLoginAttempts(user *model.User, max int) *model.AppError { + if user.FailedAttempts >= max { return model.NewAppError("checkUserLoginAttempts", "api.user.check_user_login_attempts.too_many.app_error", nil, "user_id="+user.Id, http.StatusUnauthorized) } return nil } -func checkEmailVerified(user *model.User) *model.AppError { - if !user.EmailVerified && utils.Cfg.EmailSettings.RequireEmailVerification { - return model.NewAppError("Login", "api.user.login.not_verified.app_error", nil, "user_id="+user.Id, http.StatusUnauthorized) - } - return nil -} - func checkUserNotDisabled(user *model.User) *model.AppError { if user.DeleteAt > 0 { return model.NewAppError("Login", "api.user.login.inactive.app_error", nil, "user_id="+user.Id, http.StatusUnauthorized) diff --git a/app/oauth.go b/app/oauth.go index f3ecdac54..99794482a 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -275,7 +275,7 @@ func (a *App) newSession(appName string, user *model.User) (*model.Session, *mod return nil, model.NewAppError("newSession", "api.oauth.get_access_token.internal_session.app_error", nil, "", http.StatusInternalServerError) } else { session = result.Data.(*model.Session) - AddSessionToCache(session) + a.AddSessionToCache(session) } return session, nil diff --git a/app/oauth_test.go b/app/oauth_test.go index 81f331657..d5fbe8f5e 100644 --- a/app/oauth_test.go +++ b/app/oauth_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/mattermost/mattermost-server/model" - "github.com/mattermost/mattermost-server/utils" ) func TestOAuthRevokeAccessToken(t *testing.T) { @@ -50,11 +49,11 @@ func TestOAuthDeleteApp(t *testing.T) { th := Setup() defer th.TearDown() - oldSetting := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider - defer func() { - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = oldSetting - }() - utils.Cfg.ServiceSettings.EnableOAuthServiceProvider = true + oldSetting := th.App.Config().ServiceSettings.EnableOAuthServiceProvider + defer th.App.UpdateConfig(func(cfg *model.Config) { + cfg.ServiceSettings.EnableOAuthServiceProvider = oldSetting + }) + th.App.Config().ServiceSettings.EnableOAuthServiceProvider = true a1 := &model.OAuthApp{} a1.CreatorId = model.NewId() diff --git a/app/plugins.go b/app/plugins.go index 59c9e4c25..c2f3c4785 100644 --- a/app/plugins.go +++ b/app/plugins.go @@ -33,7 +33,7 @@ type PluginAPI struct { } func (api *PluginAPI) LoadPluginConfiguration(dest interface{}) error { - if b, err := json.Marshal(utils.Cfg.PluginSettings.Plugins[api.id]); err != nil { + if b, err := json.Marshal(api.app.Config().PluginSettings.Plugins[api.id]); err != nil { return err } else { return json.Unmarshal(b, dest) @@ -145,7 +145,7 @@ type BuiltInPluginAPI struct { } func (api *BuiltInPluginAPI) LoadPluginConfiguration(dest interface{}) error { - if b, err := json.Marshal(utils.Cfg.PluginSettings.Plugins[api.id]); err != nil { + if b, err := json.Marshal(api.app.Config().PluginSettings.Plugins[api.id]); err != nil { return err } else { return json.Unmarshal(b, dest) diff --git a/app/saml.go b/app/saml.go index e6a688d8e..2fdb30e99 100644 --- a/app/saml.go +++ b/app/saml.go @@ -52,59 +52,56 @@ func WriteSamlFile(fileData *multipart.FileHeader) *model.AppError { return nil } -func AddSamlPublicCertificate(fileData *multipart.FileHeader) *model.AppError { +func (a *App) AddSamlPublicCertificate(fileData *multipart.FileHeader) *model.AppError { if err := WriteSamlFile(fileData); err != nil { return err } - cfg := &model.Config{} - *cfg = *utils.Cfg - + cfg := a.Config().Clone() *cfg.SamlSettings.PublicCertificateFile = fileData.Filename if err := cfg.IsValid(); err != nil { return err } - utils.SaveConfig(utils.CfgFileName, cfg) + a.UpdateConfig(func(dest *model.Config) { *dest = *cfg }) + utils.SaveConfig(a.ConfigFileName(), cfg) return nil } -func AddSamlPrivateCertificate(fileData *multipart.FileHeader) *model.AppError { +func (a *App) AddSamlPrivateCertificate(fileData *multipart.FileHeader) *model.AppError { if err := WriteSamlFile(fileData); err != nil { return err } - cfg := &model.Config{} - *cfg = *utils.Cfg - + cfg := a.Config().Clone() *cfg.SamlSettings.PrivateKeyFile = fileData.Filename if err := cfg.IsValid(); err != nil { return err } - utils.SaveConfig(utils.CfgFileName, cfg) + a.UpdateConfig(func(dest *model.Config) { *dest = *cfg }) + utils.SaveConfig(a.ConfigFileName(), cfg) return nil } -func AddSamlIdpCertificate(fileData *multipart.FileHeader) *model.AppError { +func (a *App) AddSamlIdpCertificate(fileData *multipart.FileHeader) *model.AppError { if err := WriteSamlFile(fileData); err != nil { return err } - cfg := &model.Config{} - *cfg = *utils.Cfg - + cfg := a.Config().Clone() *cfg.SamlSettings.IdpCertificateFile = fileData.Filename if err := cfg.IsValid(); err != nil { return err } - utils.SaveConfig(utils.CfgFileName, cfg) + a.UpdateConfig(func(dest *model.Config) { *dest = *cfg }) + utils.SaveConfig(a.ConfigFileName(), cfg) return nil } @@ -123,14 +120,12 @@ func RemoveSamlFile(filename string) *model.AppError { return nil } -func RemoveSamlPublicCertificate() *model.AppError { - if err := RemoveSamlFile(*utils.Cfg.SamlSettings.PublicCertificateFile); err != nil { +func (a *App) RemoveSamlPublicCertificate() *model.AppError { + if err := RemoveSamlFile(*a.Config().SamlSettings.PublicCertificateFile); err != nil { return err } - cfg := &model.Config{} - *cfg = *utils.Cfg - + cfg := a.Config().Clone() *cfg.SamlSettings.PublicCertificateFile = "" *cfg.SamlSettings.Encrypt = false @@ -138,19 +133,18 @@ func RemoveSamlPublicCertificate() *model.AppError { return err } - utils.SaveConfig(utils.CfgFileName, cfg) + a.UpdateConfig(func(dest *model.Config) { *dest = *cfg }) + utils.SaveConfig(a.ConfigFileName(), cfg) return nil } -func RemoveSamlPrivateCertificate() *model.AppError { - if err := RemoveSamlFile(*utils.Cfg.SamlSettings.PrivateKeyFile); err != nil { +func (a *App) RemoveSamlPrivateCertificate() *model.AppError { + if err := RemoveSamlFile(*a.Config().SamlSettings.PrivateKeyFile); err != nil { return err } - cfg := &model.Config{} - *cfg = *utils.Cfg - + cfg := a.Config().Clone() *cfg.SamlSettings.PrivateKeyFile = "" *cfg.SamlSettings.Encrypt = false @@ -158,19 +152,18 @@ func RemoveSamlPrivateCertificate() *model.AppError { return err } - utils.SaveConfig(utils.CfgFileName, cfg) + a.UpdateConfig(func(dest *model.Config) { *dest = *cfg }) + utils.SaveConfig(a.ConfigFileName(), cfg) return nil } -func RemoveSamlIdpCertificate() *model.AppError { - if err := RemoveSamlFile(*utils.Cfg.SamlSettings.IdpCertificateFile); err != nil { +func (a *App) RemoveSamlIdpCertificate() *model.AppError { + if err := RemoveSamlFile(*a.Config().SamlSettings.IdpCertificateFile); err != nil { return err } - cfg := &model.Config{} - *cfg = *utils.Cfg - + cfg := a.Config().Clone() *cfg.SamlSettings.IdpCertificateFile = "" *cfg.SamlSettings.Enable = false @@ -178,17 +171,18 @@ func RemoveSamlIdpCertificate() *model.AppError { return err } - utils.SaveConfig(utils.CfgFileName, cfg) + a.UpdateConfig(func(dest *model.Config) { *dest = *cfg }) + utils.SaveConfig(a.ConfigFileName(), cfg) return nil } -func GetSamlCertificateStatus() *model.SamlCertificateStatus { +func (a *App) GetSamlCertificateStatus() *model.SamlCertificateStatus { status := &model.SamlCertificateStatus{} - status.IdpCertificateFile = utils.FileExistsInConfigFolder(*utils.Cfg.SamlSettings.IdpCertificateFile) - status.PrivateKeyFile = utils.FileExistsInConfigFolder(*utils.Cfg.SamlSettings.PrivateKeyFile) - status.PublicCertificateFile = utils.FileExistsInConfigFolder(*utils.Cfg.SamlSettings.PublicCertificateFile) + status.IdpCertificateFile = utils.FileExistsInConfigFolder(*a.Config().SamlSettings.IdpCertificateFile) + status.PrivateKeyFile = utils.FileExistsInConfigFolder(*a.Config().SamlSettings.PrivateKeyFile) + status.PublicCertificateFile = utils.FileExistsInConfigFolder(*a.Config().SamlSettings.PublicCertificateFile) return status } diff --git a/app/server.go b/app/server.go index f8dca6a4c..8a001462a 100644 --- a/app/server.go +++ b/app/server.go @@ -53,11 +53,12 @@ func (rl *RecoveryLogger) Println(i ...interface{}) { } type CorsWrapper struct { + config model.ConfigFunc router *mux.Router } func (cw *CorsWrapper) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if len(*utils.Cfg.ServiceSettings.AllowCorsFrom) > 0 { + if len(*cw.config().ServiceSettings.AllowCorsFrom) > 0 { if utils.OriginChecker(r) { w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin")) @@ -88,25 +89,6 @@ func (m *VaryBy) Key(r *http.Request) string { return utils.GetIpAddress(r) } -func initalizeThrottledVaryBy() *throttled.VaryBy { - vary := throttled.VaryBy{} - - if utils.Cfg.RateLimitSettings.VaryByRemoteAddr { - vary.RemoteAddr = true - } - - if len(utils.Cfg.RateLimitSettings.VaryByHeader) > 0 { - vary.Headers = strings.Fields(utils.Cfg.RateLimitSettings.VaryByHeader) - - if utils.Cfg.RateLimitSettings.VaryByRemoteAddr { - l4g.Warn(utils.T("api.server.start_server.rate.warn")) - vary.RemoteAddr = false - } - } - - return &vary -} - func redirectHTTPToHTTPS(w http.ResponseWriter, r *http.Request) { if r.Host == "" { http.Error(w, "Not Found", http.StatusNotFound) @@ -121,7 +103,7 @@ func redirectHTTPToHTTPS(w http.ResponseWriter, r *http.Request) { func (a *App) StartServer() { l4g.Info(utils.T("api.server.start_server.starting.info")) - var handler http.Handler = &CorsWrapper{a.Srv.Router} + var handler http.Handler = &CorsWrapper{a.Config, a.Srv.Router} if *a.Config().RateLimitSettings.Enable { l4g.Info(utils.T("api.server.start_server.rate.info")) diff --git a/app/session.go b/app/session.go index 209604dc5..523f34747 100644 --- a/app/session.go +++ b/app/session.go @@ -12,8 +12,6 @@ import ( l4g "github.com/alecthomas/log4go" ) -var sessionCache *utils.Cache = utils.NewLru(model.SESSION_CACHE_SIZE) - func (a *App) CreateSession(session *model.Session) (*model.Session, *model.AppError) { session.Token = "" @@ -22,7 +20,7 @@ func (a *App) CreateSession(session *model.Session) (*model.Session, *model.AppE } else { session := result.Data.(*model.Session) - AddSessionToCache(session) + a.AddSessionToCache(session) return session, nil } @@ -32,7 +30,7 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { metrics := a.Metrics var session *model.Session - if ts, ok := sessionCache.Get(token); ok { + if ts, ok := a.sessionCache.Get(token); ok { session = ts.(*model.Session) if metrics != nil { metrics.IncrementMemCacheHitCounterSession() @@ -53,7 +51,7 @@ func (a *App) GetSession(token string) (*model.Session, *model.AppError) { } if !session.IsExpired() { - AddSessionToCache(session) + a.AddSessionToCache(session) } } } @@ -132,13 +130,13 @@ func (a *App) ClearSessionCacheForUser(userId string) { } func (a *App) ClearSessionCacheForUserSkipClusterSend(userId string) { - keys := sessionCache.Keys() + keys := a.sessionCache.Keys() for _, key := range keys { - if ts, ok := sessionCache.Get(key); ok { + if ts, ok := a.sessionCache.Get(key); ok { session := ts.(*model.Session) if session.UserId == userId { - sessionCache.Remove(key) + a.sessionCache.Remove(key) } } } @@ -146,12 +144,12 @@ func (a *App) ClearSessionCacheForUserSkipClusterSend(userId string) { a.InvalidateWebConnSessionCacheForUser(userId) } -func AddSessionToCache(session *model.Session) { - sessionCache.AddWithExpiresInSecs(session.Token, session, int64(*utils.Cfg.ServiceSettings.SessionCacheInMinutes*60)) +func (a *App) AddSessionToCache(session *model.Session) { + a.sessionCache.AddWithExpiresInSecs(session.Token, session, int64(*a.Config().ServiceSettings.SessionCacheInMinutes*60)) } -func SessionCacheLength() int { - return sessionCache.Len() +func (a *App) SessionCacheLength() int { + return a.sessionCache.Len() } func (a *App) RevokeSessionsForDeviceId(userId string, deviceId string, currentSessionId string) *model.AppError { @@ -227,7 +225,7 @@ func (a *App) UpdateLastActivityAtIfNeeded(session model.Session) { } session.LastActivityAt = now - AddSessionToCache(&session) + a.AddSessionToCache(&session) } func (a *App) CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError) { @@ -301,7 +299,7 @@ func (a *App) createSessionForUserAccessToken(tokenString string) (*model.Sessio } else { session := result.Data.(*model.Session) - AddSessionToCache(session) + a.AddSessionToCache(session) return session, nil } diff --git a/app/session_test.go b/app/session_test.go index 5915b932d..97abb540a 100644 --- a/app/session_test.go +++ b/app/session_test.go @@ -23,16 +23,16 @@ func TestCache(t *testing.T) { UserId: model.NewId(), } - sessionCache.AddWithExpiresInSecs(session.Token, session, 5*60) + th.App.sessionCache.AddWithExpiresInSecs(session.Token, session, 5*60) - keys := sessionCache.Keys() + keys := th.App.sessionCache.Keys() if len(keys) <= 0 { t.Fatal("should have items") } th.App.ClearSessionCacheForUser(session.UserId) - rkeys := sessionCache.Keys() + rkeys := th.App.sessionCache.Keys() if len(rkeys) != len(keys)-1 { t.Fatal("should have one less") } diff --git a/app/user.go b/app/user.go index a38c61554..87b21fb92 100644 --- a/app/user.go +++ b/app/user.go @@ -159,7 +159,7 @@ func IsUserSignUpAllowed() *model.AppError { } func (a *App) IsFirstUserAccount() bool { - if SessionCacheLength() == 0 { + if a.SessionCacheLength() == 0 { if cr := <-a.Srv.Store.User().GetTotalUsersCount(); cr.Err != nil { l4g.Error(cr.Err) return false diff --git a/app/user_test.go b/app/user_test.go index 39be7eafa..282e2896d 100644 --- a/app/user_test.go +++ b/app/user_test.go @@ -87,11 +87,11 @@ func TestCreateOAuthUser(t *testing.T) { th.App.PermanentDeleteUser(user) - userCreation := utils.Cfg.TeamSettings.EnableUserCreation - defer func() { - utils.Cfg.TeamSettings.EnableUserCreation = userCreation - }() - utils.Cfg.TeamSettings.EnableUserCreation = false + userCreation := th.App.Config().TeamSettings.EnableUserCreation + defer th.App.UpdateConfig(func(cfg *model.Config) { + cfg.TeamSettings.EnableUserCreation = userCreation + }) + th.App.Config().TeamSettings.EnableUserCreation = false _, err = th.App.CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id) if err == nil { diff --git a/jobs/server.go b/jobs/server.go index 8c5ee807d..40cfb1f64 100644 --- a/jobs/server.go +++ b/jobs/server.go @@ -13,6 +13,7 @@ import ( ) type JobServer struct { + Config model.ConfigFunc Store store.Store Workers *Workers Schedulers *Schedulers @@ -23,6 +24,13 @@ type JobServer struct { LdapSync ejobs.LdapSyncInterface } +func NewJobServer(config model.ConfigFunc, store store.Store) *JobServer { + return &JobServer{ + Config: config, + Store: store, + } +} + func (srv *JobServer) LoadLicense() { licenseId := "" if result := <-srv.Store.System().Get(); result.Err == nil { diff --git a/jobs/workers.go b/jobs/workers.go index c984a43b8..415553981 100644 --- a/jobs/workers.go +++ b/jobs/workers.go @@ -13,6 +13,7 @@ import ( type Workers struct { startOnce sync.Once + Config model.ConfigFunc Watcher *Watcher DataRetention model.Worker @@ -24,7 +25,9 @@ type Workers struct { } func (srv *JobServer) InitWorkers() *Workers { - workers := &Workers{} + workers := &Workers{ + Config: srv.Config, + } workers.Watcher = srv.MakeWatcher(workers, DEFAULT_WATCHER_POLLING_INTERVAL) if srv.DataRetentionJob != nil { @@ -50,19 +53,19 @@ func (workers *Workers) Start() *Workers { l4g.Info("Starting workers") workers.startOnce.Do(func() { - if workers.DataRetention != nil && (*utils.Cfg.DataRetentionSettings.EnableMessageDeletion || *utils.Cfg.DataRetentionSettings.EnableFileDeletion) { + if workers.DataRetention != nil && (*workers.Config().DataRetentionSettings.EnableMessageDeletion || *workers.Config().DataRetentionSettings.EnableFileDeletion) { go workers.DataRetention.Run() } - if workers.ElasticsearchIndexing != nil && *utils.Cfg.ElasticsearchSettings.EnableIndexing { + if workers.ElasticsearchIndexing != nil && *workers.Config().ElasticsearchSettings.EnableIndexing { go workers.ElasticsearchIndexing.Run() } - if workers.ElasticsearchAggregation != nil && *utils.Cfg.ElasticsearchSettings.EnableIndexing { + if workers.ElasticsearchAggregation != nil && *workers.Config().ElasticsearchSettings.EnableIndexing { go workers.ElasticsearchAggregation.Run() } - if workers.LdapSync != nil && *utils.Cfg.LdapSettings.Enable { + if workers.LdapSync != nil && *workers.Config().LdapSettings.Enable { go workers.LdapSync.Run() } @@ -113,19 +116,19 @@ func (workers *Workers) Stop() *Workers { workers.Watcher.Stop() - if workers.DataRetention != nil && (*utils.Cfg.DataRetentionSettings.EnableMessageDeletion || *utils.Cfg.DataRetentionSettings.EnableFileDeletion) { + if workers.DataRetention != nil && (*workers.Config().DataRetentionSettings.EnableMessageDeletion || *workers.Config().DataRetentionSettings.EnableFileDeletion) { workers.DataRetention.Stop() } - if workers.ElasticsearchIndexing != nil && *utils.Cfg.ElasticsearchSettings.EnableIndexing { + if workers.ElasticsearchIndexing != nil && *workers.Config().ElasticsearchSettings.EnableIndexing { workers.ElasticsearchIndexing.Stop() } - if workers.ElasticsearchAggregation != nil && *utils.Cfg.ElasticsearchSettings.EnableIndexing { + if workers.ElasticsearchAggregation != nil && *workers.Config().ElasticsearchSettings.EnableIndexing { workers.ElasticsearchAggregation.Stop() } - if workers.LdapSync != nil && *utils.Cfg.LdapSettings.Enable { + if workers.LdapSync != nil && *workers.Config().LdapSettings.Enable { workers.LdapSync.Stop() } diff --git a/model/config.go b/model/config.go index 9871a13b4..768009d94 100644 --- a/model/config.go +++ b/model/config.go @@ -522,6 +522,8 @@ type PluginSettings struct { PluginStates map[string]*PluginState } +type ConfigFunc func() *Config + type Config struct { ServiceSettings ServiceSettings TeamSettings TeamSettings diff --git a/utils/config.go b/utils/config.go index 8611be975..7b7a111d6 100644 --- a/utils/config.go +++ b/utils/config.go @@ -285,7 +285,7 @@ func InitAndLoadConfig(filename string) error { // LoadConfig will try to search around for the corresponding config file. // It will search /tmp/fileName then attempt ./config/fileName, // then ../config/fileName and last it will look at fileName -func LoadConfig(fileName string) { +func LoadConfig(fileName string) *model.Config { cfgMutex.Lock() defer cfgMutex.Unlock() @@ -394,6 +394,8 @@ func LoadConfig(fileName string) { for _, listener := range cfgListeners { listener(&oldConfig, &config) } + + return &config } func RegenerateClientConfig() { diff --git a/web/web.go b/web/web.go index 77a0c107a..1724fd3f2 100644 --- a/web/web.go +++ b/web/web.go @@ -21,14 +21,14 @@ func Init(api3 *api.API) { mainrouter := api3.BaseRoutes.Root - if *utils.Cfg.ServiceSettings.WebserverMode != "disabled" { + if *api3.App.Config().ServiceSettings.WebserverMode != "disabled" { staticDir, _ := utils.FindDir(model.CLIENT_DIR) l4g.Debug("Using client directory at %v", staticDir) staticHandler := staticHandler(http.StripPrefix("/static/", http.FileServer(http.Dir(staticDir)))) - pluginHandler := pluginHandler(http.StripPrefix("/static/plugins/", http.FileServer(http.Dir(staticDir+"plugins/")))) + pluginHandler := pluginHandler(api3.App.Config, http.StripPrefix("/static/plugins/", http.FileServer(http.Dir(staticDir+"plugins/")))) - if *utils.Cfg.ServiceSettings.WebserverMode == "gzip" { + if *api3.App.Config().ServiceSettings.WebserverMode == "gzip" { staticHandler = gziphandler.GzipHandler(staticHandler) pluginHandler = gziphandler.GzipHandler(pluginHandler) } @@ -50,9 +50,9 @@ func staticHandler(handler http.Handler) http.Handler { }) } -func pluginHandler(handler http.Handler) http.Handler { +func pluginHandler(config model.ConfigFunc, handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if *utils.Cfg.ServiceSettings.EnableDeveloper { + if *config().ServiceSettings.EnableDeveloper { w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") } else { w.Header().Set("Cache-Control", "max-age=31556926, public") -- cgit v1.2.3-1-g7c22