diff --git a/api4/apitestlib.go b/api4/apitestlib.go index 3699b6209d..e48dbfdcae 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -102,7 +102,7 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent } th := &TestHelper{ - App: s.FakeApp(), + App: app.New(app.ServerConnector(s)), Server: s, ConfigStore: memoryStore, IncludeCacheLayer: includeCache, @@ -131,7 +131,7 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent Init(th.Server, th.Server.AppOptions, th.App.Srv().Router) InitLocal(th.Server, th.Server.AppOptions, th.App.Srv().LocalRouter) web.New(th.Server, th.Server.AppOptions, th.App.Srv().Router) - wsapi.Init(th.App, th.App.Srv().WebSocketRouter) + wsapi.Init(th.App.Srv()) th.App.DoAppMigrations() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) @@ -146,9 +146,9 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent }) if enterprise { - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) } else { - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) } th.Client = th.CreateClient() @@ -170,6 +170,8 @@ func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, ent th.tempWorkspace = tempWorkspace } + th.App.InitServer() + return th } @@ -265,7 +267,7 @@ func (me *TestHelper) TearDown() { utils.DisableDebugLogForTest() if me.IncludeCacheLayer { // Clean all the caches - me.App.InvalidateAllCaches() + me.App.Srv().InvalidateAllCaches() } me.ShutdownApp() diff --git a/api4/channel.go b/api4/channel.go index d02de7eea6..ba8cdc4914 100644 --- a/api4/channel.go +++ b/api4/channel.go @@ -1546,7 +1546,7 @@ func updateChannelScheme(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("new_scheme_id", schemeID) - if c.App.License() == nil { + if c.App.Srv().License() == nil { c.Err = model.NewAppError("Api4.UpdateChannelScheme", "api.channel.update_channel_scheme.license.error", nil, "", http.StatusNotImplemented) return } @@ -1640,7 +1640,7 @@ func channelMembersMinusGroupMembers(c *Context, w http.ResponseWriter, r *http. } func channelMemberCountsByGroup(c *Context, w http.ResponseWriter, r *http.Request) { - if c.App.License() == nil { + if c.App.Srv().License() == nil { c.Err = model.NewAppError("Api4.channelMemberCountsByGroup", "api.channel.channel_member_counts_by_group.license.error", nil, "", http.StatusNotImplemented) return } @@ -1673,7 +1673,7 @@ func channelMemberCountsByGroup(c *Context, w http.ResponseWriter, r *http.Reque } func getChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) { - if c.App.License() == nil { + if c.App.Srv().License() == nil { c.Err = model.NewAppError("Api4.GetChannelModerations", "api.channel.get_channel_moderations.license.error", nil, "", http.StatusNotImplemented) return } @@ -1710,7 +1710,7 @@ func getChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) { } func patchChannelModerations(c *Context, w http.ResponseWriter, r *http.Request) { - if c.App.License() == nil { + if c.App.Srv().License() == nil { c.Err = model.NewAppError("Api4.patchChannelModerations", "api.channel.patch_channel_moderations.license.error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/channel_test.go b/api4/channel_test.go index b5d036b8cb..196b69e8f0 100644 --- a/api4/channel_test.go +++ b/api4/channel_test.go @@ -430,10 +430,10 @@ func TestCreateDirectChannelAsGuest(t *testing.T) { enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable defer func() { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts }) - th.App.RemoveLicense() + th.App.Srv().RemoveLicense() }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) id := model.NewId() guest := &model.User{ @@ -557,10 +557,10 @@ func TestCreateGroupChannelAsGuest(t *testing.T) { enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable defer func() { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts }) - th.App.RemoveLicense() + th.App.Srv().RemoveLicense() }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) id := model.NewId() guest := &model.User{ @@ -2373,7 +2373,7 @@ func TestAddChannelMember(t *testing.T) { Client.Logout() th.MakeUserChannelAdmin(user, privateChannel) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() Client.Login(user.Username, user.Password) _, resp = Client.AddChannelMember(privateChannel.Id, user3.Id) @@ -2622,7 +2622,7 @@ func TestRemoveChannelMember(t *testing.T) { th.LoginBasic() th.UpdateUserToNonTeamAdmin(user1, team) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() // Check the appropriate permissions are enforced. defaultRolePermissions := th.SaveDefaultRolePermissions() @@ -2660,7 +2660,7 @@ func TestRemoveChannelMember(t *testing.T) { CheckForbiddenStatus(t, resp) th.MakeUserChannelAdmin(user1, privateChannel) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() _, resp = Client.RemoveUserFromChannel(privateChannel.Id, user2.Id) CheckNoError(t, resp) @@ -2902,10 +2902,10 @@ func TestAutocompleteChannelsForSearchGuestUsers(t *testing.T) { enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable defer func() { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts }) - th.App.RemoveLicense() + th.App.Srv().RemoveLicense() }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) id := model.NewId() guest := &model.User{ @@ -3028,7 +3028,7 @@ func TestUpdateChannelScheme(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("")) + th.App.Srv().SetLicense(model.NewTestLicense("")) th.App.SetPhase2PermissionsMigrationStatus(true) @@ -3085,10 +3085,10 @@ func TestUpdateChannelScheme(t *testing.T) { CheckForbiddenStatus(t, resp) // Test that a license is required. - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, channelScheme.Id) CheckNotImplementedStatus(t, resp) - th.App.SetLicense(model.NewTestLicense("")) + th.App.Srv().SetLicense(model.NewTestLicense("")) // Test an invalid scheme scope. _, resp = th.SystemAdminClient.UpdateChannelScheme(channel.Id, teamScheme.Id) @@ -3251,14 +3251,14 @@ func TestGetChannelModerations(t *testing.T) { require.Equal(t, "api.channel.get_channel_moderations.license.error", res.Error.Id) }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) t.Run("Errors as a non sysadmin", func(t *testing.T) { _, res := th.Client.GetChannelModerations(channel.Id, "") require.Equal(t, "api.context.permissions.app_error", res.Error.Id) }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) t.Run("Returns default moderations with default roles", func(t *testing.T) { moderations, res := th.SystemAdminClient.GetChannelModerations(channel.Id, "") @@ -3420,14 +3420,14 @@ func TestPatchChannelModerations(t *testing.T) { require.Equal(t, "api.channel.patch_channel_moderations.license.error", res.Error.Id) }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) t.Run("Errors as a non sysadmin", func(t *testing.T) { _, res := th.Client.PatchChannelModerations(channel.Id, emptyPatch) require.Equal(t, "api.context.permissions.app_error", res.Error.Id) }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) t.Run("Returns default moderations with empty patch", func(t *testing.T) { moderations, res := th.SystemAdminClient.PatchChannelModerations(channel.Id, emptyPatch) @@ -3592,7 +3592,7 @@ func TestGetChannelMemberCountsByGroup(t *testing.T) { require.Equal(t, "api.channel.channel_member_counts_by_group.license.error", res.Error.Id) }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) t.Run("Errors without read permission to the channel", func(t *testing.T) { _, res := th.Client.GetChannelMemberCountsByGroup(model.NewId(), false, "") diff --git a/api4/cors_test.go b/api4/cors_test.go index b71b0fba12..5faed407d5 100644 --- a/api4/cors_test.go +++ b/api4/cors_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/mattermost/mattermost-server/v5/model" + "github.com/mattermost/mattermost-server/v5/store/storetest/mocks" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -125,6 +126,12 @@ func TestCORSRequestHandling(t *testing.T) { *cfg.ServiceSettings.CorsAllowCredentials = testcase.CorsAllowCredentials }) defer th.TearDown() + systemStore := mocks.SystemStore{} + systemStore.On("Get").Return(make(model.StringMap), nil) + licenseStore := mocks.LicenseStore{} + licenseStore.On("Get", "").Return(&model.LicenseRecord{}, nil) + th.App.Srv().Store.(*mocks.Store).On("System").Return(&systemStore) + th.App.Srv().Store.(*mocks.Store).On("License").Return(&licenseStore) port := th.App.Srv().ListenAddr.Port host := fmt.Sprintf("http://localhost:%v", port) diff --git a/api4/group.go b/api4/group.go index 3ba8c2c4ad..408bd6ced3 100644 --- a/api4/group.go +++ b/api4/group.go @@ -79,7 +79,7 @@ func getGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -119,7 +119,7 @@ func patchGroup(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("patchGroup", audit.Fail) defer c.LogAuditRec(auditRec) - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.patchGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -219,7 +219,7 @@ func linkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.createGroupSyncable", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -275,7 +275,7 @@ func getGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { } syncableType := c.Params.SyncableType - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getGroupSyncable", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -312,7 +312,7 @@ func getGroupSyncables(c *Context, w http.ResponseWriter, r *http.Request) { } syncableType := c.Params.SyncableType - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getGroupSyncables", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -374,7 +374,7 @@ func patchGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.patchGroupSyncable", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return @@ -440,7 +440,7 @@ func unlinkGroupSyncable(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("syncable_id", syncableID) auditRec.AddMeta("syncable_type", syncableType) - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.unlinkGroupSyncable", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -499,7 +499,7 @@ func getGroupMembers(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getGroupMembers", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -541,7 +541,7 @@ func getGroupsByUserId(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getGroupsByUserId", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -567,7 +567,7 @@ func getGroupsByChannel(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getGroupsByChannel", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -625,7 +625,7 @@ func getGroupsByTeam(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getGroupsByTeam", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -667,7 +667,7 @@ func getGroupsAssociatedToChannelsByTeam(c *Context, w http.ResponseWriter, r *h return } - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getGroupsAssociatedToChannelsByTeam", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -702,7 +702,7 @@ func getGroupsAssociatedToChannelsByTeam(c *Context, w http.ResponseWriter, r *h } func getGroups(c *Context, w http.ResponseWriter, r *http.Request) { - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getGroups", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/group_test.go b/api4/group_test.go index 64d6b9a6f4..e4367ea079 100644 --- a/api4/group_test.go +++ b/api4/group_test.go @@ -34,7 +34,7 @@ func TestGetGroup(t *testing.T) { _, response = th.SystemAdminClient.GetGroup(g.Id, "") CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) group, response := th.SystemAdminClient.GetGroup(g.Id, "") CheckNoError(t, response) @@ -91,7 +91,7 @@ func TestPatchGroup(t *testing.T) { _, response = th.SystemAdminClient.PatchGroup(g.Id, gp) CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) group2, response := th.SystemAdminClient.PatchGroup(g.Id, gp) CheckOKStatus(t, response) @@ -149,7 +149,7 @@ func TestLinkGroupTeam(t *testing.T) { _, response = th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) _, response = th.Client.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) assert.NotNil(t, response.Error) @@ -187,7 +187,7 @@ func TestLinkGroupChannel(t *testing.T) { _, response = th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) groupTeam, response := th.Client.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) assert.Equal(t, http.StatusCreated, response.StatusCode) @@ -220,12 +220,12 @@ func TestUnlinkGroupTeam(t *testing.T) { AutoAdd: model.NewBool(true), } - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) _, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) assert.Equal(t, http.StatusCreated, response.StatusCode) - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) response = th.Client.UnlinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam) CheckNotImplementedStatus(t, response) @@ -233,7 +233,7 @@ func TestUnlinkGroupTeam(t *testing.T) { response = th.SystemAdminClient.UnlinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam) CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) response = th.Client.UnlinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam) assert.NotNil(t, response.Error) @@ -267,12 +267,12 @@ func TestUnlinkGroupChannel(t *testing.T) { AutoAdd: model.NewBool(true), } - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) _, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) assert.Equal(t, http.StatusCreated, response.StatusCode) - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) response = th.Client.UnlinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel) CheckNotImplementedStatus(t, response) @@ -280,7 +280,7 @@ func TestUnlinkGroupChannel(t *testing.T) { response = th.SystemAdminClient.UnlinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel) CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) _, response = th.SystemAdminClient.UpdateChannelRoles(th.BasicChannel.Id, th.BasicUser.Id, "") require.Nil(t, response.Error) @@ -319,7 +319,7 @@ func TestGetGroupTeam(t *testing.T) { _, response = th.SystemAdminClient.GetGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, "") CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) patch := &model.GroupSyncablePatch{ AutoAdd: model.NewBool(true), @@ -373,7 +373,7 @@ func TestGetGroupChannel(t *testing.T) { _, response = th.SystemAdminClient.GetGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, "") CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) patch := &model.GroupSyncablePatch{ AutoAdd: model.NewBool(true), @@ -421,7 +421,7 @@ func TestGetGroupTeams(t *testing.T) { }) assert.Nil(t, err) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) patch := &model.GroupSyncablePatch{ AutoAdd: model.NewBool(true), @@ -433,7 +433,7 @@ func TestGetGroupTeams(t *testing.T) { assert.Equal(t, http.StatusCreated, response.StatusCode) } - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, response := th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeTeam, "") CheckNotImplementedStatus(t, response) @@ -441,7 +441,7 @@ func TestGetGroupTeams(t *testing.T) { _, response = th.SystemAdminClient.GetGroupSyncables(g.Id, model.GroupSyncableTypeTeam, "") CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) _, response = th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeTeam, "") assert.Equal(t, http.StatusForbidden, response.StatusCode) @@ -470,7 +470,7 @@ func TestGetGroupChannels(t *testing.T) { }) assert.Nil(t, err) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) patch := &model.GroupSyncablePatch{ AutoAdd: model.NewBool(true), @@ -482,7 +482,7 @@ func TestGetGroupChannels(t *testing.T) { assert.Equal(t, http.StatusCreated, response.StatusCode) } - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, response := th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeChannel, "") CheckNotImplementedStatus(t, response) @@ -490,7 +490,7 @@ func TestGetGroupChannels(t *testing.T) { _, response = th.SystemAdminClient.GetGroupSyncables(g.Id, model.GroupSyncableTypeChannel, "") CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) _, response = th.Client.GetGroupSyncables(g.Id, model.GroupSyncableTypeChannel, "") assert.Equal(t, http.StatusForbidden, response.StatusCode) @@ -523,7 +523,7 @@ func TestPatchGroupTeam(t *testing.T) { AutoAdd: model.NewBool(true), } - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) groupSyncable, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) assert.Equal(t, http.StatusCreated, response.StatusCode) @@ -533,12 +533,12 @@ func TestPatchGroupTeam(t *testing.T) { _, response = th.Client.PatchGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) assert.Equal(t, http.StatusForbidden, response.StatusCode) - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) patch.AutoAdd = model.NewBool(false) groupSyncable, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicTeam.Id, model.GroupSyncableTypeTeam, patch) @@ -588,7 +588,7 @@ func TestPatchGroupChannel(t *testing.T) { AutoAdd: model.NewBool(true), } - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) groupSyncable, response := th.SystemAdminClient.LinkGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) assert.Equal(t, http.StatusCreated, response.StatusCode) @@ -607,12 +607,12 @@ func TestPatchGroupChannel(t *testing.T) { _, err = th.App.PatchRole(role, &model.RolePatch{Permissions: &originalPermissions}) require.Nil(t, err) - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) patch.AutoAdd = model.NewBool(false) groupSyncable, response = th.SystemAdminClient.PatchGroupSyncable(g.Id, th.BasicChannel.Id, model.GroupSyncableTypeChannel, patch) @@ -678,14 +678,14 @@ func TestGetGroupsByChannel(t *testing.T) { CheckBadRequestStatus(t, response) }) - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { _, _, response := client.GetGroupsByChannel(th.BasicChannel.Id, opts) CheckNotImplementedStatus(t, response) }) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) privateChannel := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE) @@ -751,12 +751,12 @@ func TestGetGroupsAssociatedToChannelsByTeam(t *testing.T) { _, response := th.SystemAdminClient.GetGroupsAssociatedToChannelsByTeam("asdfasdf", opts) CheckBadRequestStatus(t, response) - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, response = th.SystemAdminClient.GetGroupsAssociatedToChannelsByTeam(th.BasicTeam.Id, opts) CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) groups, response := th.SystemAdminClient.GetGroupsAssociatedToChannelsByTeam(th.BasicTeam.Id, opts) assert.Nil(t, response.Error) @@ -827,14 +827,14 @@ func TestGetGroupsByTeam(t *testing.T) { CheckBadRequestStatus(t, response) }) - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { _, _, response := client.GetGroupsByTeam(th.BasicTeam.Id, opts) CheckNotImplementedStatus(t, response) }) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) { groups, _, response := client.GetGroupsByTeam(th.BasicTeam.Id, opts) @@ -887,12 +887,12 @@ func TestGetGroups(t *testing.T) { }, } - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, response := th.SystemAdminClient.GetGroups(opts) CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) _, response = th.SystemAdminClient.GetGroups(opts) require.Nil(t, response.Error) @@ -995,11 +995,11 @@ func TestGetGroupsByUserId(t *testing.T) { _, err = th.App.UpsertGroupMember(group2.Id, user1.Id) assert.Nil(t, err) - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, response := th.SystemAdminClient.GetGroupsByUserId(user1.Id) CheckNotImplementedStatus(t, response) - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) _, response = th.SystemAdminClient.GetGroupsByUserId("") CheckBadRequestStatus(t, response) @@ -1028,7 +1028,7 @@ func TestGetGroupsGroupConstrainedParentTeam(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) var groups []*model.Group for i := 0; i < 4; i++ { diff --git a/api4/ldap.go b/api4/ldap.go index 0ffab97205..a5092e11a6 100644 --- a/api4/ldap.go +++ b/api4/ldap.go @@ -34,7 +34,7 @@ func (api *API) InitLdap() { } func syncLdap(c *Context, w http.ResponseWriter, r *http.Request) { - if c.App.License() == nil || !*c.App.License().Features.LDAP { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAP { c.Err = model.NewAppError("Api4.syncLdap", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -54,7 +54,7 @@ func syncLdap(c *Context, w http.ResponseWriter, r *http.Request) { } func testLdap(c *Context, w http.ResponseWriter, r *http.Request) { - if c.App.License() == nil || !*c.App.License().Features.LDAP { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAP { c.Err = model.NewAppError("Api4.testLdap", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -78,7 +78,7 @@ func getLdapGroups(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.getLdapGroups", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -139,7 +139,7 @@ func linkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("remote_id", c.Params.RemoteId) - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.linkLdapGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } @@ -236,7 +236,7 @@ func unlinkLdapGroup(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.License() == nil || !*c.App.License().Features.LDAPGroups { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.LDAPGroups { c.Err = model.NewAppError("Api4.unlinkLdapGroup", "api.ldap_groups.license_error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/ldap_test.go b/api4/ldap_test.go index afbcaeeb91..404a53d055 100644 --- a/api4/ldap_test.go +++ b/api4/ldap_test.go @@ -20,7 +20,7 @@ func TestTestLdap(t *testing.T) { require.NotNil(t, resp.Error) require.Equal(t, "api.ldap_groups.license_error", resp.Error.Id) - th.App.SetLicense(model.NewTestLicense("ldap_groups")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap_groups")) _, resp = th.Client.TestLdap() CheckForbiddenStatus(t, resp) @@ -42,7 +42,7 @@ func TestSyncLdap(t *testing.T) { require.NotNil(t, resp.Error) require.Equal(t, "api.ldap_groups.license_error", resp.Error.Id) - th.App.SetLicense(model.NewTestLicense("ldap_groups")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap_groups")) _, resp = th.SystemAdminClient.SyncLdap() CheckNoError(t, resp) diff --git a/api4/license.go b/api4/license.go index fdd8e958f6..bf1f945e05 100644 --- a/api4/license.go +++ b/api4/license.go @@ -37,9 +37,9 @@ func getClientLicense(c *Context, w http.ResponseWriter, r *http.Request) { var clientLicense map[string]string if c.App.SessionHasPermissionTo(*c.App.Session(), model.PERMISSION_MANAGE_SYSTEM) { - clientLicense = c.App.ClientLicense() + clientLicense = c.App.Srv().ClientLicense() } else { - clientLicense = c.App.GetSanitizedClientLicense() + clientLicense = c.App.Srv().GetSanitizedClientLicense() } w.Write([]byte(model.MapToJson(clientLicense))) @@ -92,7 +92,7 @@ func addLicense(c *Context, w http.ResponseWriter, r *http.Request) { buf := bytes.NewBuffer(nil) io.Copy(buf, file) - license, appErr := c.App.SaveLicense(buf.Bytes()) + license, appErr := c.App.Srv().SaveLicense(buf.Bytes()) if appErr != nil { if appErr.Id == model.EXPIRED_LICENSE_ERROR { c.LogAudit("failed - expired or non-started license") @@ -131,7 +131,7 @@ func removeLicense(c *Context, w http.ResponseWriter, r *http.Request) { return } - if err := c.App.RemoveLicense(); err != nil { + if err := c.App.Srv().RemoveLicense(); err != nil { c.Err = err return } @@ -187,7 +187,7 @@ func requestTrialLicense(c *Context, w http.ResponseWriter, r *http.Request) { Users: usersNumber.Users, } - if err := c.App.RequestTrialLicense(trialLicenseRequest); err != nil { + if err := c.App.Srv().RequestTrialLicense(trialLicenseRequest); err != nil { c.Err = err return } diff --git a/api4/license_local.go b/api4/license_local.go index b4d5b08a2a..e5cad8a389 100644 --- a/api4/license_local.go +++ b/api4/license_local.go @@ -54,7 +54,7 @@ func localAddLicense(c *Context, w http.ResponseWriter, r *http.Request) { buf := bytes.NewBuffer(nil) io.Copy(buf, file) - license, appErr := c.App.SaveLicense(buf.Bytes()) + license, appErr := c.App.Srv().SaveLicense(buf.Bytes()) if appErr != nil { if appErr.Id == model.EXPIRED_LICENSE_ERROR { c.LogAudit("failed - expired or non-started license") @@ -83,7 +83,7 @@ func localRemoveLicense(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) c.LogAudit("attempt") - if err := c.App.RemoveLicense(); err != nil { + if err := c.App.Srv().RemoveLicense(); err != nil { c.Err = err return } diff --git a/api4/plugin_test.go b/api4/plugin_test.go index ce62441ad3..a3758c2a9b 100644 --- a/api4/plugin_test.go +++ b/api4/plugin_test.go @@ -602,7 +602,7 @@ func TestGetMarketplacePlugins(t *testing.T) { l := model.NewTestLicense() // model.NewTestLicense generates a E20 license *l.Features.EnterprisePlugins = false - th.App.SetLicense(l) + th.App.Srv().SetLicense(l) plugins, resp := th.SystemAdminClient.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) CheckNoError(t, resp) @@ -628,7 +628,7 @@ func TestGetMarketplacePlugins(t *testing.T) { *cfg.PluginSettings.MarketplaceUrl = testServer.URL }) - th.App.SetLicense(model.NewTestLicense("enterprise_plugins")) + th.App.Srv().SetLicense(model.NewTestLicense("enterprise_plugins")) plugins, resp := th.SystemAdminClient.GetMarketplacePlugins(&model.MarketplacePluginFilter{}) CheckNoError(t, resp) diff --git a/api4/post.go b/api4/post.go index e3e848dd6a..8d5638c6b9 100644 --- a/api4/post.go +++ b/api4/post.go @@ -682,7 +682,7 @@ func saveIsPinnedPost(c *Context, w http.ResponseWriter, r *http.Request, isPinn return } - if c.App.License() != nil && + if c.App.Srv().License() != nil && *c.App.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL && !c.App.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { diff --git a/api4/post_test.go b/api4/post_test.go index 0a0aa2dd9a..cb8f4f1c0d 100644 --- a/api4/post_test.go +++ b/api4/post_test.go @@ -444,7 +444,7 @@ func TestCreatePostPublic(t *testing.T) { CheckForbiddenStatus(t, resp) th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_POST_ALL_PUBLIC_ROLE_ID, false) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() Client.Login(user.Email, user.Password) @@ -458,7 +458,7 @@ func TestCreatePostPublic(t *testing.T) { th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false) th.App.JoinUserToTeam(th.BasicTeam, ruser, "") th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_PUBLIC_ROLE_ID) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() Client.Login(user.Email, user.Password) @@ -491,7 +491,7 @@ func TestCreatePostAll(t *testing.T) { CheckForbiddenStatus(t, resp) th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_POST_ALL_ROLE_ID, false) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() Client.Login(user.Email, user.Password) @@ -509,7 +509,7 @@ func TestCreatePostAll(t *testing.T) { th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false) th.App.JoinUserToTeam(th.BasicTeam, ruser, "") th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_ROLE_ID) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() Client.Login(user.Email, user.Password) @@ -667,7 +667,7 @@ func TestUpdatePost(t *testing.T) { Client := th.Client channel := th.BasicChannel - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) fileIds := make([]string, 3) data, err := testutils.ReadTestFile("test.png") @@ -850,7 +850,7 @@ func TestPatchPost(t *testing.T) { Client := th.Client channel := th.BasicChannel - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) fileIds := make([]string, 3) data, err := testutils.ReadTestFile("test.png") @@ -976,10 +976,10 @@ func TestPinPost(t *testing.T) { t.Run("unable-to-pin-post-in-read-only-town-square", func(t *testing.T) { townSquareIsReadOnly := *th.App.Config().TeamSettings.ExperimentalTownSquareIsReadOnly - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true }) - defer th.App.RemoveLicense() + defer th.App.Srv().RemoveLicense() defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = townSquareIsReadOnly }) channel, err := th.App.GetChannelByName("town-square", th.BasicTeam.Id, true) diff --git a/api4/reaction_test.go b/api4/reaction_test.go index 0593b0d1b8..f15750fcf8 100644 --- a/api4/reaction_test.go +++ b/api4/reaction_test.go @@ -161,7 +161,7 @@ func TestSaveReaction(t *testing.T) { assert.Nil(t, err) post := th.CreatePostWithClient(th.Client, channel) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true }) reaction := &model.Reaction{ @@ -177,7 +177,7 @@ func TestSaveReaction(t *testing.T) { require.Nil(t, err) require.Equal(t, 0, len(reactions), "should have not created a reaction") - th.App.RemoveLicense() + th.App.Srv().RemoveLicense() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = false }) }) @@ -486,7 +486,7 @@ func TestDeleteReaction(t *testing.T) { assert.Nil(t, err) post := th.CreatePostWithClient(th.Client, channel) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) reaction := &model.Reaction{ UserId: userId, @@ -510,7 +510,7 @@ func TestDeleteReaction(t *testing.T) { require.Nil(t, err) require.Equal(t, 1, len(reactions), "should have not deleted a reaction") - th.App.RemoveLicense() + th.App.Srv().RemoveLicense() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = false }) }) diff --git a/api4/role.go b/api4/role.go index f0f52f4e80..9114a4c65b 100644 --- a/api4/role.go +++ b/api4/role.go @@ -101,7 +101,7 @@ func patchRole(c *Context, w http.ResponseWriter, r *http.Request) { } auditRec.AddMeta("role", oldRole) - if c.App.License() == nil && patch.Permissions != nil { + if c.App.Srv().License() == nil && patch.Permissions != nil { if oldRole.Name == "system_guest" || oldRole.Name == "team_guest" || oldRole.Name == "channel_guest" { c.Err = model.NewAppError("Api4.PatchRoles", "api.roles.patch_roles.license.error", nil, "", http.StatusNotImplemented) return @@ -134,7 +134,7 @@ func patchRole(c *Context, w http.ResponseWriter, r *http.Request) { } } - if c.App.License() != nil && (oldRole.Name == "system_guest" || oldRole.Name == "team_guest" || oldRole.Name == "channel_guest") && !*c.App.License().Features.GuestAccountsPermissions { + if c.App.Srv().License() != nil && (oldRole.Name == "system_guest" || oldRole.Name == "team_guest" || oldRole.Name == "channel_guest") && !*c.App.Srv().License().Features.GuestAccountsPermissions { c.Err = model.NewAppError("Api4.PatchRoles", "api.roles.patch_roles.license.error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/role_test.go b/api4/role_test.go index fd8d14ffde..e97b70384f 100644 --- a/api4/role_test.go +++ b/api4/role_test.go @@ -196,7 +196,7 @@ func TestPatchRole(t *testing.T) { // Add a license. license := model.NewTestLicense() license.Features.GuestAccountsPermissions = model.NewBool(false) - th.App.SetLicense(license) + th.App.Srv().SetLicense(license) // Try again, should succeed received, resp = th.SystemAdminClient.PatchRole(role.Id, patch) @@ -212,7 +212,7 @@ func TestPatchRole(t *testing.T) { t.Run("Check guest permissions editing without E20 license", func(t *testing.T) { license := model.NewTestLicense() license.Features.GuestAccountsPermissions = model.NewBool(false) - th.App.SetLicense(license) + th.App.Srv().SetLicense(license) guestRole, err := th.App.Srv().Store.Role().GetByName("system_guest") require.Nil(t, err) @@ -223,7 +223,7 @@ func TestPatchRole(t *testing.T) { t.Run("Check guest permissions editing with E20 license", func(t *testing.T) { license := model.NewTestLicense() license.Features.GuestAccountsPermissions = model.NewBool(true) - th.App.SetLicense(license) + th.App.Srv().SetLicense(license) guestRole, err := th.App.Srv().Store.Role().GetByName("system_guest") require.Nil(t, err) _, resp = th.SystemAdminClient.PatchRole(guestRole.Id, patch) diff --git a/api4/scheme.go b/api4/scheme.go index 183d22190f..e65720af36 100644 --- a/api4/scheme.go +++ b/api4/scheme.go @@ -31,7 +31,7 @@ func createScheme(c *Context, w http.ResponseWriter, r *http.Request) { defer c.LogAuditRec(auditRec) auditRec.AddMeta("scheme", scheme) - if c.App.License() == nil || !*c.App.License().Features.CustomPermissionsSchemes { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.CustomPermissionsSchemes { c.Err = model.NewAppError("Api4.CreateScheme", "api.scheme.create_scheme.license.error", nil, "", http.StatusNotImplemented) return } @@ -172,7 +172,7 @@ func patchScheme(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("patchScheme", audit.Fail) defer c.LogAuditRec(auditRec) - if c.App.License() == nil || !*c.App.License().Features.CustomPermissionsSchemes { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.CustomPermissionsSchemes { c.Err = model.NewAppError("Api4.PatchScheme", "api.scheme.patch_scheme.license.error", nil, "", http.StatusNotImplemented) return } @@ -211,7 +211,7 @@ func deleteScheme(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("deleteScheme", audit.Fail) defer c.LogAuditRec(auditRec) - if c.App.License() == nil || !*c.App.License().Features.CustomPermissionsSchemes { + if c.App.Srv().License() == nil || !*c.App.Srv().License().Features.CustomPermissionsSchemes { c.Err = model.NewAppError("Api4.DeleteScheme", "api.scheme.delete_scheme.license.error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/scheme_test.go b/api4/scheme_test.go index 07a4db7bee..16155e5652 100644 --- a/api4/scheme_test.go +++ b/api4/scheme_test.go @@ -17,7 +17,7 @@ func TestCreateScheme(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.SetPhase2PermissionsMigrationStatus(true) @@ -135,7 +135,7 @@ func TestCreateScheme(t *testing.T) { CheckForbiddenStatus(t, r5) // Try and create a scheme without a license. - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) scheme6 := &model.Scheme{ DisplayName: model.NewId(), Name: model.NewId(), @@ -148,7 +148,7 @@ func TestCreateScheme(t *testing.T) { th.App.SetPhase2PermissionsMigrationStatus(false) th.LoginSystemAdmin() - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) scheme7 := &model.Scheme{ DisplayName: model.NewId(), @@ -164,7 +164,7 @@ func TestGetScheme(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) // Basic test of creating a team scheme. scheme1 := &model.Scheme{ @@ -209,7 +209,7 @@ func TestGetScheme(t *testing.T) { CheckUnauthorizedStatus(t, r5) th.SystemAdminClient.Login(th.SystemAdminUser.Username, th.SystemAdminUser.Password) - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, r6 := th.SystemAdminClient.GetScheme(s1.Id) CheckNoError(t, r6) @@ -226,7 +226,7 @@ func TestGetSchemes(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) scheme1 := &model.Scheme{ DisplayName: model.NewId(), @@ -289,7 +289,7 @@ func TestGetTeamsForScheme(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.SetPhase2PermissionsMigrationStatus(true) @@ -381,7 +381,7 @@ func TestGetChannelsForScheme(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.SetPhase2PermissionsMigrationStatus(true) @@ -475,7 +475,7 @@ func TestPatchScheme(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.SetPhase2PermissionsMigrationStatus(true) @@ -565,14 +565,14 @@ func TestPatchScheme(t *testing.T) { CheckForbiddenStatus(t, r10) // Test without license. - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, r11 := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch) CheckNotImplementedStatus(t, r11) th.App.SetPhase2PermissionsMigrationStatus(false) th.LoginSystemAdmin() - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) _, r12 := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch) CheckNotImplementedStatus(t, r12) @@ -583,7 +583,7 @@ func TestDeleteScheme(t *testing.T) { defer th.TearDown() t.Run("ValidTeamScheme", func(t *testing.T) { - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.SetPhase2PermissionsMigrationStatus(true) @@ -661,7 +661,7 @@ func TestDeleteScheme(t *testing.T) { }) t.Run("ValidChannelScheme", func(t *testing.T) { - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.SetPhase2PermissionsMigrationStatus(true) @@ -721,7 +721,7 @@ func TestDeleteScheme(t *testing.T) { }) t.Run("FailureCases", func(t *testing.T) { - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) th.App.SetPhase2PermissionsMigrationStatus(true) @@ -748,13 +748,13 @@ func TestDeleteScheme(t *testing.T) { CheckForbiddenStatus(t, r4) // Test without license. - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, r5 := th.SystemAdminClient.DeleteScheme(s1.Id) CheckNotImplementedStatus(t, r5) th.App.SetPhase2PermissionsMigrationStatus(false) - th.App.SetLicense(model.NewTestLicense("custom_permissions_schemes")) + th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes")) _, r6 := th.SystemAdminClient.DeleteScheme(s1.Id) CheckNotImplementedStatus(t, r6) diff --git a/api4/system.go b/api4/system.go index 1ed4ff731e..bed235090a 100644 --- a/api4/system.go +++ b/api4/system.go @@ -108,7 +108,7 @@ func getSystemPing(c *Context, w http.ResponseWriter, r *http.Request) { filestoreStatusKey := "filestore_status" s[filestoreStatusKey] = model.STATUS_OK - license := c.App.License() + license := c.App.Srv().License() backend, appErr := filesstore.NewFileBackend(&c.App.Config().FileSettings, license != nil && *license.Features.Compliance) if appErr == nil { appErr = backend.TestConnection() @@ -240,7 +240,7 @@ func invalidateCaches(c *Context, w http.ResponseWriter, r *http.Request) { return } - err := c.App.InvalidateAllCaches() + err := c.App.Srv().InvalidateAllCaches() if err != nil { c.Err = err return @@ -379,7 +379,7 @@ func testS3(c *Context, w http.ResponseWriter, r *http.Request) { cfg.FileSettings.AmazonS3SecretAccessKey = c.App.Config().FileSettings.AmazonS3SecretAccessKey } - license := c.App.License() + license := c.App.Srv().License() backend, appErr := filesstore.NewFileBackend(&cfg.FileSettings, license != nil && *license.Features.Compliance) if appErr == nil { appErr = backend.TestConnection() diff --git a/api4/team.go b/api4/team.go index 855cee8911..76ba79fbdd 100644 --- a/api4/team.go +++ b/api4/team.go @@ -1220,7 +1220,7 @@ func inviteUsersToTeam(c *Context, w http.ResponseWriter, r *http.Request) { func inviteGuestsToChannels(c *Context, w http.ResponseWriter, r *http.Request) { graceful := r.URL.Query().Get("graceful") != "" - if c.App.License() == nil { + if c.App.Srv().License() == nil { c.Err = model.NewAppError("Api4.InviteGuestsToChannels", "api.team.invate_guests_to_channels.license.error", nil, "", http.StatusNotImplemented) return } @@ -1455,7 +1455,7 @@ func updateTeamScheme(c *Context, w http.ResponseWriter, r *http.Request) { auditRec := c.MakeAuditRecord("updateTeamScheme", audit.Fail) defer c.LogAuditRec(auditRec) - if c.App.License() == nil { + if c.App.Srv().License() == nil { c.Err = model.NewAppError("Api4.UpdateTeamScheme", "api.team.update_team_scheme.license.error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/team_test.go b/api4/team_test.go index 7e3b67d55b..9fd0771d12 100644 --- a/api4/team_test.go +++ b/api4/team_test.go @@ -1647,8 +1647,8 @@ func TestAddTeamMember(t *testing.T) { team := th.BasicTeam otherUser := th.CreateUser() - th.App.SetLicense(model.NewTestLicense("")) - defer th.App.SetLicense(nil) + th.App.Srv().SetLicense(model.NewTestLicense("")) + defer th.App.Srv().SetLicense(nil) enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable defer func() { @@ -1731,7 +1731,7 @@ func TestAddTeamMember(t *testing.T) { // Update user to team admin th.UpdateUserToTeamAdmin(th.BasicUser, th.BasicTeam) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() th.LoginBasic() // Should work as a team admin. @@ -1745,7 +1745,7 @@ func TestAddTeamMember(t *testing.T) { th.RemovePermissionFromRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_ADMIN_ROLE_ID) th.UpdateUserToNonTeamAdmin(th.BasicUser, th.BasicTeam) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() th.LoginBasic() // Should work as a regular user. @@ -1800,8 +1800,8 @@ func TestAddTeamMember(t *testing.T) { th.App.DeleteToken(token) // by invite_id - th.App.SetLicense(model.NewTestLicense("")) - defer th.App.SetLicense(nil) + th.App.Srv().SetLicense(model.NewTestLicense("")) + defer th.App.Srv().SetLicense(nil) _, resp = Client.Login(guest.Email, guest.Password) CheckNoError(t, resp) @@ -2094,7 +2094,7 @@ func TestAddTeamMembers(t *testing.T) { // Update user to team admin th.UpdateUserToTeamAdmin(th.BasicUser, th.BasicTeam) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() th.LoginBasic() // Should work as a team admin. @@ -2108,7 +2108,7 @@ func TestAddTeamMembers(t *testing.T) { th.RemovePermissionFromRole(model.PERMISSION_ADD_USER_TO_TEAM.Id, model.TEAM_ADMIN_ROLE_ID) th.UpdateUserToNonTeamAdmin(th.BasicUser, th.BasicTeam) - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() th.LoginBasic() // Should work as a regular user. @@ -2755,7 +2755,7 @@ func TestInviteGuestsToTeam(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { cfg.GuestAccountsSettings.Enable = &enableGuestAccounts }) }() - th.App.SetLicense(model.NewTestLicense("")) + th.App.Srv().SetLicense(model.NewTestLicense("")) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = false }) _, resp := th.SystemAdminClient.InviteGuestsToTeam(th.BasicTeam.Id, emailList, []string{th.BasicChannel.Id}, "test-message") @@ -2768,13 +2768,13 @@ func TestInviteGuestsToTeam(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableEmailInvitations = true }) - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, resp = th.SystemAdminClient.InviteGuestsToTeam(th.BasicTeam.Id, emailList, []string{th.BasicChannel.Id}, "test-message") require.NotNil(t, resp.Error, "Should be disabled") - th.App.SetLicense(model.NewTestLicense("")) - defer th.App.SetLicense(nil) + th.App.Srv().SetLicense(model.NewTestLicense("")) + defer th.App.Srv().SetLicense(nil) okMsg, resp := th.SystemAdminClient.InviteGuestsToTeam(th.BasicTeam.Id, emailList, []string{th.BasicChannel.Id}, "test-message") CheckNoError(t, resp) @@ -2973,7 +2973,7 @@ func TestUpdateTeamScheme(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("")) + th.App.Srv().SetLicense(model.NewTestLicense("")) th.App.SetPhase2PermissionsMigrationStatus(true) @@ -3025,10 +3025,10 @@ func TestUpdateTeamScheme(t *testing.T) { CheckForbiddenStatus(t, resp) // Test that a license is required. - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) _, resp = th.SystemAdminClient.UpdateTeamScheme(team.Id, teamScheme.Id) CheckNotImplementedStatus(t, resp) - th.App.SetLicense(model.NewTestLicense("")) + th.App.Srv().SetLicense(model.NewTestLicense("")) // Test an invalid scheme scope. _, resp = th.SystemAdminClient.UpdateTeamScheme(team.Id, channelScheme.Id) diff --git a/api4/terms_of_service.go b/api4/terms_of_service.go index 0cd71e72da..2e01c6f39f 100644 --- a/api4/terms_of_service.go +++ b/api4/terms_of_service.go @@ -32,7 +32,7 @@ func createTermsOfService(c *Context, w http.ResponseWriter, r *http.Request) { return } - if license := c.App.License(); license == nil || !*license.Features.CustomTermsOfService { + if license := c.App.Srv().License(); license == nil || !*license.Features.CustomTermsOfService { c.Err = model.NewAppError("createTermsOfService", "api.create_terms_of_service.custom_terms_of_service_disabled.app_error", nil, "", http.StatusBadRequest) return } diff --git a/api4/terms_of_service_test.go b/api4/terms_of_service_test.go index 392702ef5e..3bb8f38c84 100644 --- a/api4/terms_of_service_test.go +++ b/api4/terms_of_service_test.go @@ -45,7 +45,7 @@ func TestCreateTermsOfServiceAdminUser(t *testing.T) { termsOfService, resp := Client.CreateTermsOfService("terms of service new", th.SystemAdminUser.Id) CheckErrorMessage(t, resp, "api.create_terms_of_service.custom_terms_of_service_disabled.app_error") - th.App.SetLicense(model.NewTestLicense("EnableCustomTermsOfService")) + th.App.Srv().SetLicense(model.NewTestLicense("EnableCustomTermsOfService")) termsOfService, resp = Client.CreateTermsOfService("terms of service new_2", th.SystemAdminUser.Id) CheckNoError(t, resp) diff --git a/api4/user.go b/api4/user.go index be5bb2c206..f4f17f4d0b 100644 --- a/api4/user.go +++ b/api4/user.go @@ -113,7 +113,7 @@ func createUser(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("token_type", token.Type) if token.Type == app.TOKEN_TYPE_GUEST_INVITATION { - if c.App.License() == nil { + if c.App.Srv().License() == nil { c.Err = model.NewAppError("CreateUserWithToken", "api.user.create_user.guest_accounts.license.app_error", nil, "", http.StatusBadRequest) return } @@ -1469,7 +1469,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) { ldapOnly := props["ldap_only"] == "true" if *c.App.Config().ExperimentalSettings.ClientSideCertEnable { - if license := c.App.License(); license == nil || !*license.Features.SAML { + if license := c.App.Srv().License(); license == nil || !*license.Features.SAML { c.Err = model.NewAppError("ClientSideCertNotAllowed", "api.user.login.client_side_cert.license.app_error", nil, "", http.StatusBadRequest) return } @@ -1503,7 +1503,7 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) { auditRec.AddMeta("user", user) if user.IsGuest() { - if c.App.License() == nil { + if c.App.Srv().License() == nil { c.Err = model.NewAppError("login", "api.user.login.guest_accounts.license.error", nil, "", http.StatusUnauthorized) return } @@ -2232,7 +2232,7 @@ func demoteUserToGuest(c *Context, w http.ResponseWriter, r *http.Request) { return } - if c.App.License() == nil { + if c.App.Srv().License() == nil { c.Err = model.NewAppError("Api4.demoteUserToGuest", "api.team.demote_user_to_guest.license.error", nil, "", http.StatusNotImplemented) return } diff --git a/api4/user_test.go b/api4/user_test.go index 28f24f4f3c..493788a1aa 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -337,7 +337,7 @@ func TestCreateUserWebSocketEvent(t *testing.T) { defer th.TearDown() t.Run("guest should not received new_user event but user should", func(t *testing.T) { - th.App.SetLicense(model.NewTestLicense("guests")) + th.App.Srv().SetLicense(model.NewTestLicense("guests")) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.AllowEmailAccounts = true }) @@ -2332,7 +2332,7 @@ func TestUpdateUserMfa(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("mfa")) + th.App.Srv().SetLicense(model.NewTestLicense("mfa")) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) session, _ := th.App.GetSession(th.Client.AuthToken) @@ -2372,7 +2372,7 @@ func TestCheckUserMfa(t *testing.T) { require.False(t, required, "mfa not active") - th.App.SetLicense(model.NewTestLicense("mfa")) + th.App.Srv().SetLicense(model.NewTestLicense("mfa")) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) th.LoginBasic() @@ -2478,7 +2478,7 @@ func TestGenerateMfaSecret(t *testing.T) { _, resp = th.Client.GenerateMfaSecret("junk") CheckBadRequestStatus(t, resp) - th.App.SetLicense(model.NewTestLicense("mfa")) + th.App.Srv().SetLicense(model.NewTestLicense("mfa")) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) _, resp = th.Client.GenerateMfaSecret(model.NewId()) @@ -3130,7 +3130,7 @@ func TestCBALogin(t *testing.T) { t.Run("primary", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("saml")) + th.App.Srv().SetLicense(model.NewTestLicense("saml")) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true @@ -3188,7 +3188,7 @@ func TestCBALogin(t *testing.T) { t.Run("secondary", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("saml")) + th.App.Srv().SetLicense(model.NewTestLicense("saml")) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableBotAccountCreation = true @@ -3256,7 +3256,7 @@ func TestSwitchAccount(t *testing.T) { require.NotEmpty(t, link, "bad link") - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = false }) sr = &model.SwitchRequest{ @@ -4607,10 +4607,10 @@ func TestDemoteUserToGuest(t *testing.T) { enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable defer func() { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts }) - th.App.RemoveLicense() + th.App.Srv().RemoveLicense() }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) _, respErr := th.SystemAdminClient.GetUser(user.Id, "") CheckNoError(t, respErr) _, respErr = th.SystemAdminClient.DemoteUserToGuest(user.Id) @@ -4660,10 +4660,10 @@ func TestPromoteGuestToUser(t *testing.T) { enableGuestAccounts := *th.App.Config().GuestAccountsSettings.Enable defer func() { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = enableGuestAccounts }) - th.App.RemoveLicense() + th.App.Srv().RemoveLicense() }() th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GuestAccountsSettings.Enable = true }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) _, respErr := th.SystemAdminClient.GetUser(user.Id, "") CheckNoError(t, respErr) _, respErr = th.SystemAdminClient.PromoteGuestToUser(user.Id) diff --git a/app/admin.go b/app/admin.go index e0fa4e6b5e..20a57c3004 100644 --- a/app/admin.go +++ b/app/admin.go @@ -20,25 +20,25 @@ import ( "github.com/mattermost/mattermost-server/v5/utils" ) -func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) { +func (s *Server) GetLogs(page, perPage int) ([]string, *model.AppError) { var lines []string - if a.Cluster() != nil && *a.Config().ClusterSettings.Enable { + if s.Cluster != nil && *s.Config().ClusterSettings.Enable { lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, "-----------------------------------------------------------------------------------------------------------") - lines = append(lines, a.Cluster().GetMyClusterInfo().Hostname) + lines = append(lines, s.Cluster.GetMyClusterInfo().Hostname) lines = append(lines, "-----------------------------------------------------------------------------------------------------------") lines = append(lines, "-----------------------------------------------------------------------------------------------------------") } - melines, err := a.GetLogsSkipSend(page, perPage) + melines, err := s.GetLogsSkipSend(page, perPage) if err != nil { return nil, err } lines = append(lines, melines...) - if a.Cluster() != nil && *a.Config().ClusterSettings.Enable { - clines, err := a.Cluster().GetLogs(page, perPage) + if s.Cluster != nil && *s.Config().ClusterSettings.Enable { + clines, err := s.Cluster.GetLogs(page, perPage) if err != nil { return nil, err } @@ -49,11 +49,15 @@ func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) { return lines, nil } -func (a *App) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) { +func (a *App) GetLogs(page, perPage int) ([]string, *model.AppError) { + return a.Srv().GetLogs(page, perPage) +} + +func (s *Server) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) { var lines []string - if *a.Config().LogSettings.EnableFile { - logFile := utils.GetLogFileLocation(*a.Config().LogSettings.FileLocation) + if *s.Config().LogSettings.EnableFile { + logFile := utils.GetLogFileLocation(*s.Config().LogSettings.FileLocation) file, err := os.Open(logFile) if err != nil { return nil, model.NewAppError("getLogs", "api.admin.file_read_error", nil, err.Error(), http.StatusInternalServerError) @@ -120,6 +124,10 @@ func (a *App) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) { return lines, nil } +func (a *App) GetLogsSkipSend(page, perPage int) ([]string, *model.AppError) { + return a.Srv().GetLogsSkipSend(page, perPage) +} + func (a *App) GetClusterStatus() []*model.ClusterInfo { infos := make([]*model.ClusterInfo, 0) @@ -130,11 +138,11 @@ func (a *App) GetClusterStatus() []*model.ClusterInfo { return infos } -func (a *App) InvalidateAllCaches() *model.AppError { +func (s *Server) InvalidateAllCaches() *model.AppError { debug.FreeOSMemory() - a.InvalidateAllCachesSkipSend() + s.InvalidateAllCachesSkipSend() - if a.Cluster() != nil { + if s.Cluster != nil { msg := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_INVALIDATE_ALL_CACHES, @@ -142,23 +150,23 @@ func (a *App) InvalidateAllCaches() *model.AppError { WaitForAllToSend: true, } - a.Cluster().SendClusterMessage(msg) + s.Cluster.SendClusterMessage(msg) } return nil } -func (a *App) InvalidateAllCachesSkipSend() { +func (s *Server) InvalidateAllCachesSkipSend() { mlog.Info("Purging all caches") - a.Srv().sessionCache.Purge() - a.Srv().statusCache.Purge() - a.Srv().Store.Team().ClearCaches() - a.Srv().Store.Channel().ClearCaches() - a.Srv().Store.User().ClearCaches() - a.Srv().Store.Post().ClearCaches() - a.Srv().Store.FileInfo().ClearCaches() - a.Srv().Store.Webhook().ClearCaches() - a.LoadLicense() + s.sessionCache.Purge() + s.statusCache.Purge() + s.Store.Team().ClearCaches() + s.Store.Channel().ClearCaches() + s.Store.User().ClearCaches() + s.Store.Post().ClearCaches() + s.Store.FileInfo().ClearCaches() + s.Store.Webhook().ClearCaches() + s.LoadLicense() } func (a *App) RecycleDatabaseConnection() { @@ -212,7 +220,7 @@ func (a *App) TestEmail(userId string, cfg *model.Config) *model.AppError { } T := utils.GetUserTranslations(user.Locale) - license := a.License() + license := a.Srv().License() if err := mailservice.SendMailUsingConfig(user.Email, T("api.admin.test_email.subject"), T("api.admin.test_email.body"), cfg, license != nil && *license.Features.Compliance); err != nil { return model.NewAppError("testEmail", "app.admin.test_email.failure", map[string]interface{}{"Error": err.Error()}, "", http.StatusInternalServerError) } diff --git a/app/app.go b/app/app.go index a910f9d25b..db2d1308c7 100644 --- a/app/app.go +++ b/app/app.go @@ -11,7 +11,6 @@ import ( goi18n "github.com/mattermost/go-i18n/i18n" "github.com/mattermost/mattermost-server/v5/einterfaces" - "github.com/mattermost/mattermost-server/v5/jobs" "github.com/mattermost/mattermost-server/v5/mlog" "github.com/mattermost/mattermost-server/v5/model" "github.com/mattermost/mattermost-server/v5/services/httpservice" @@ -63,6 +62,68 @@ func New(options ...AppOption) *App { return app } +func (a *App) InitServer() { + a.srv.AppInitializedOnce.Do(func() { + a.initEnterprise() + a.accountMigration = a.srv.AccountMigration + a.ldap = a.srv.Ldap + a.notification = a.srv.Notification + a.saml = a.srv.Saml + + a.StartPushNotificationsHubWorkers() + a.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) { + if *oldConfig.GuestAccountsSettings.Enable && !*newConfig.GuestAccountsSettings.Enable { + if appErr := a.DeactivateGuests(); appErr != nil { + mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) + } + } + }) + + // Disable active guest accounts on first run if guest accounts are disabled + if !*a.Config().GuestAccountsSettings.Enable { + if appErr := a.DeactivateGuests(); appErr != nil { + mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) + } + } + + pluginsRoute := a.srv.Router.PathPrefix("/plugins/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() + pluginsRoute.HandleFunc("", a.ServePluginRequest) + pluginsRoute.HandleFunc("/public/{public_file:.*}", a.ServePluginPublicRequest) + pluginsRoute.HandleFunc("/{anything:.*}", a.ServePluginRequest) + a.srv.Router.NotFoundHandler = http.HandlerFunc(a.Handle404) + + // Scheduler must be started before cluster. + a.initJobs() + + if a.srv.joinCluster && a.srv.Cluster != nil { + a.registerAllClusterMessageHandlers() + } + + a.DoAppMigrations() + + a.InitPostMetadata() + + a.InitPlugins(*a.Config().PluginSettings.Directory, *a.Config().PluginSettings.ClientDirectory) + a.AddConfigListener(func(prevCfg, cfg *model.Config) { + if *cfg.PluginSettings.Enable { + a.InitPlugins(*cfg.PluginSettings.Directory, *a.Config().PluginSettings.ClientDirectory) + } else { + a.srv.ShutDownPlugins() + } + }) + if a.Srv().runjobs { + a.Srv().Go(func() { + runLicenseExpirationCheckJob(a) + }) + } + a.srv.RunJobs() + }) + a.accountMigration = a.srv.AccountMigration + a.ldap = a.srv.Ldap + a.notification = a.srv.Notification + a.saml = a.srv.Saml +} + // DO NOT CALL THIS. // This is to avoid having to change all the code in cmd/mattermost/commands/* for now // shutdown should be called directly on the server @@ -71,38 +132,18 @@ func (a *App) Shutdown() { a.srv = nil } -func (a *App) configOrLicenseListener() { - a.regenerateClientConfig() -} - -func (s *Server) initJobs() { - s.Jobs = jobs.NewJobServer(s, s.Store) - if jobsDataRetentionJobInterface != nil { - s.Jobs.DataRetentionJob = jobsDataRetentionJobInterface(s) - } - if jobsMessageExportJobInterface != nil { - s.Jobs.MessageExportJob = jobsMessageExportJobInterface(s) - } - if jobsElasticsearchAggregatorInterface != nil { - s.Jobs.ElasticsearchAggregator = jobsElasticsearchAggregatorInterface(s) - } - if jobsElasticsearchIndexerInterface != nil { - s.Jobs.ElasticsearchIndexer = jobsElasticsearchIndexerInterface(s) - } +func (a *App) initJobs() { if jobsLdapSyncInterface != nil { - s.Jobs.LdapSync = jobsLdapSyncInterface(s.FakeApp()) + a.srv.Jobs.LdapSync = jobsLdapSyncInterface(a) } if jobsMigrationsInterface != nil { - s.Jobs.Migrations = jobsMigrationsInterface(s.FakeApp()) + a.srv.Jobs.Migrations = jobsMigrationsInterface(a) } if jobsPluginsInterface != nil { - s.Jobs.Plugins = jobsPluginsInterface(s.FakeApp()) + a.srv.Jobs.Plugins = jobsPluginsInterface(a) } - if jobsBleveIndexerInterface != nil { - s.Jobs.BleveIndexer = jobsBleveIndexerInterface(s) - } - s.Jobs.Workers = s.Jobs.InitWorkers() - s.Jobs.Schedulers = s.Jobs.InitSchedulers() + a.srv.Jobs.Workers = a.srv.Jobs.InitWorkers() + a.srv.Jobs.Schedulers = a.srv.Jobs.InitSchedulers() } func (a *App) DiagnosticId() string { @@ -113,9 +154,9 @@ func (a *App) SetDiagnosticId(id string) { a.Srv().diagnosticId = id } -func (a *App) HTMLTemplates() *template.Template { - if a.Srv().htmlTemplateWatcher != nil { - return a.Srv().htmlTemplateWatcher.Templates() +func (s *Server) HTMLTemplates() *template.Template { + if s.htmlTemplateWatcher != nil { + return s.htmlTemplateWatcher.Templates() } return nil @@ -133,8 +174,8 @@ func (a *App) Handle404(w http.ResponseWriter, r *http.Request) { utils.RenderWebAppError(a.Config(), w, r, model.NewAppError("Handle404", "api.context.404.app_error", nil, "", http.StatusNotFound), a.AsymmetricSigningKey()) } -func (a *App) getSystemInstallDate() (int64, *model.AppError) { - systemData, appErr := a.Srv().Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY) +func (s *Server) getSystemInstallDate() (int64, *model.AppError) { + systemData, appErr := s.Store.System().GetByName(model.SYSTEM_INSTALLATION_DATE_KEY) if appErr != nil { return 0, appErr } @@ -145,8 +186,8 @@ func (a *App) getSystemInstallDate() (int64, *model.AppError) { return value, nil } -func (a *App) getFirstServerRunTimestamp() (int64, *model.AppError) { - systemData, appErr := a.Srv().Store.System().GetByName(model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY) +func (s *Server) getFirstServerRunTimestamp() (int64, *model.AppError) { + systemData, appErr := s.Store.System().GetByName(model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY) if appErr != nil { return 0, appErr } diff --git a/app/app_iface.go b/app/app_iface.go index dce0e3015b..471307b8aa 100644 --- a/app/app_iface.go +++ b/app/app_iface.go @@ -11,7 +11,6 @@ import ( "bytes" "context" "crypto/ecdsa" - "html/template" "io" "mime/multipart" "net/http" @@ -160,8 +159,6 @@ type AppIface interface { GetEnvironmentConfig() map[string]interface{} // GetGroupsByTeam returns the paged list and the total count of group associated to the given team. GetGroupsByTeam(teamId string, opts model.GroupSearchOpts) ([]*model.GroupWithSchemeAdmin, int, *model.AppError) - // GetHubForUserId returns the hub for a given user id. - GetHubForUserId(userId string) *Hub // GetKnownUsers returns the list of user ids of users with any direct // relationship with a user. That means any user sharing any channel, including // direct and group channels. @@ -204,8 +201,6 @@ type AppIface interface { HubRegister(webConn *WebConn) // HubStart starts all the hubs. HubStart() - // HubStop stops all the hubs. - HubStop() // HubUnregister unregisters a connection from a hub. HubUnregister(webConn *WebConn) // InstallMarketplacePlugin installs a plugin listed in the marketplace server. It will get the plugin bundle @@ -217,8 +212,6 @@ type AppIface interface { InstallPluginWithSignature(pluginFile, signature io.ReadSeeker) (*model.Manifest, *model.AppError) // IsUsernameTaken checks if the username is already used by another user. Return false if the username is invalid. IsUsernameTaken(name string) bool - // License returns the currently active license or nil if the application is unlicensed. - License() *model.License // LimitedClientConfigWithComputed gets the configuration in a format suitable for sending to the client. LimitedClientConfigWithComputed() map[string]string // LogAuditRec logs an audit record using default CLILevel. @@ -253,8 +246,6 @@ type AppIface interface { RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError) // RenameTeam is used to rename the team Name and the DisplayName fields RenameTeam(team *model.Team, newTeamName string, newDisplayName string) (*model.Team, *model.AppError) - // RequestTrialLicense request a trial license from the mattermost offical license server - RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError // RevokeSessionsFromAllUsers will go through all the sessions active // in the server and revoke them RevokeSessionsFromAllUsers() *model.AppError @@ -341,7 +332,6 @@ type AppIface interface { AddChannelMember(userId string, channel *model.Channel, userRequestorId string, postRootId string) (*model.ChannelMember, *model.AppError) AddConfigListener(listener func(*model.Config, *model.Config)) string AddDirectChannels(teamId string, user *model.User) *model.AppError - AddLicenseListener(listener func(oldLicense, newLicense *model.License)) string AddNotificationEmailToBatch(user *model.User, post *model.Post, team *model.Team) *model.AppError AddSamlIdpCertificate(fileData *multipart.FileHeader) *model.AppError AddSamlPrivateCertificate(fileData *multipart.FileHeader) *model.AppError @@ -394,7 +384,6 @@ type AppIface interface { ClearTeamMembersCache(teamID string) ClientConfig() map[string]string ClientConfigHash() string - ClientLicense() map[string]string Cluster() einterfaces.ClusterInterface CompareAndDeletePluginKey(pluginId string, key string, oldValue []byte) (bool, *model.AppError) CompareAndSetPluginKey(pluginId string, key string, oldValue, newValue []byte) (bool, *model.AppError) @@ -560,6 +549,7 @@ type AppIface interface { GetGroupsByIDs(groupIDs []string) ([]*model.Group, *model.AppError) GetGroupsBySource(groupSource model.GroupSource) ([]*model.Group, *model.AppError) GetGroupsByUserId(userId string) ([]*model.Group, *model.AppError) + GetHubForUserId(userId string) *Hub GetIncomingWebhook(hookId string) (*model.IncomingWebhook, *model.AppError) GetIncomingWebhooksForTeamPage(teamId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) GetIncomingWebhooksForTeamPageByUser(teamId string, userId string, page, perPage int) ([]*model.IncomingWebhook, *model.AppError) @@ -631,7 +621,6 @@ type AppIface interface { GetSamlMetadata() (string, *model.AppError) GetSamlMetadataFromIdp(idpMetadataUrl string) (*model.SamlMetadataResponse, *model.AppError) GetSanitizeOptions(asAdmin bool) map[string]bool - GetSanitizedClientLicense() map[string]string GetScheme(id string) (*model.Scheme, *model.AppError) GetSchemeByName(name string) (*model.Scheme, *model.AppError) GetSchemeRolesForTeam(teamId string) (string, string, string, *model.AppError) @@ -696,7 +685,6 @@ type AppIface interface { GetUsersWithoutTeamPage(options *model.UserGetOptions, asAdmin bool) ([]*model.User, *model.AppError) GetVerifyEmailToken(token string) (*model.Token, *model.AppError) GetViewUsersRestrictions(userId string) (*model.ViewUsersRestrictions, *model.AppError) - HTMLTemplates() *template.Template HTTPService() httpservice.HTTPService Handle404(w http.ResponseWriter, r *http.Request) HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) @@ -710,15 +698,15 @@ type AppIface interface { HasPermissionToChannelByPost(askingUserId string, postId string, permission *model.Permission) bool HasPermissionToTeam(askingUserId string, teamId string, permission *model.Permission) bool HasPermissionToUser(askingUserId string, userId string) bool + HubStop() ImageProxy() *imageproxy.ImageProxy ImageProxyAdder() func(string) string ImageProxyRemover() (f func(string) string) ImportPermissions(jsonl io.Reader) error InitPlugins(pluginDir, webappPluginDir string) InitPostMetadata() + InitServer() InstallPluginFromData(data model.PluginEventData) - InvalidateAllCaches() *model.AppError - InvalidateAllCachesSkipSend() InvalidateAllEmailInvites() *model.AppError InvalidateCacheForUser(userId string) InvalidateWebConnSessionCacheForUser(userId string) @@ -744,7 +732,6 @@ type AppIface interface { ListDirectory(path string) ([]string, *model.AppError) ListPluginKeys(pluginId string, page, perPage int) ([]string, *model.AppError) ListTeamCommands(teamId string) ([]*model.Command, *model.AppError) - LoadLicense() Log() *mlog.Logger LoginByOAuth(service string, userData io.Reader, teamId string) (*model.User, *model.AppError) MakePermissionError(permission *model.Permission) *model.AppError @@ -799,8 +786,6 @@ type AppIface interface { ReloadConfig() error RemoveConfigListener(id string) RemoveFile(path string) *model.AppError - RemoveLicense() *model.AppError - RemoveLicenseListener(id string) RemovePlugin(id string) *model.AppError RemovePluginFromData(data model.PluginEventData) RemoveSamlIdpCertificate() *model.AppError @@ -831,7 +816,6 @@ type AppIface interface { SaveAndBroadcastStatus(status *model.Status) SaveBrandImage(imageData *multipart.FileHeader) *model.AppError SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) - SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) SaveUserTermsOfService(userId, termsOfServiceId string, accepted bool) *model.AppError SchemesIterator(scope string, batchSize int) func() []*model.Scheme @@ -856,9 +840,7 @@ type AppIface interface { SendAckToPushProxy(ack *model.PushNotificationAck) error SendAutoResponse(channel *model.Channel, receiver *model.User) (bool, *model.AppError) SendAutoResponseIfNecessary(channel *model.Channel, sender *model.User) (bool, *model.AppError) - SendDailyDiagnostics() SendDeactivateAccountEmail(email string, locale, siteURL string) *model.AppError - SendDiagnostic(event string, properties map[string]interface{}) SendEmailVerification(user *model.User, newEmail string) *model.AppError SendEphemeralPost(userId string, post *model.Post) *model.Post SendInviteEmails(team *model.Team, senderName string, senderUserId string, invites []string, siteURL string) @@ -880,12 +862,10 @@ type AppIface interface { SetAcceptLanguage(s string) SetActiveChannel(userId string, channelId string) *model.AppError SetAutoResponderStatus(user *model.User, oldNotifyProps model.StringMap) - SetClientLicense(m map[string]string) SetContext(c context.Context) SetDefaultProfileImage(user *model.User) *model.AppError SetDiagnosticId(id string) SetIpAddress(s string) - SetLicense(license *model.License) bool SetLog(l *mlog.Logger) SetPath(s string) SetPhase2PermissionsMigrationStatus(isComplete bool) error @@ -911,8 +891,6 @@ type AppIface interface { SetTeamIconFromFile(team *model.Team, file io.Reader) *model.AppError SetTeamIconFromMultiPartFile(teamId string, file multipart.File) *model.AppError SetUserAgent(s string) - SetupInviteEmailRateLimiting() error - ShutDownPlugins() SlackAddBotUser(teamId string, log *bytes.Buffer) *model.User SlackAddChannels(teamId string, slackchannels []SlackChannel, posts map[string][]SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User, importerLog *bytes.Buffer) map[string]*model.Channel SlackAddPosts(teamId string, channel *model.Channel, posts []SlackPost, users map[string]*model.User, uploads map[string]*zip.File, botUser *model.User) @@ -922,7 +900,6 @@ type AppIface interface { SoftDeleteTeam(teamId string) *model.AppError Srv() *Server StartPushNotificationsHubWorkers() - StopPushNotificationsHubWorkers() SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError) @@ -987,7 +964,6 @@ type AppIface interface { UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError) UserAgent() string UserCanSeeOtherUser(userId string, otherUserId string) (bool, *model.AppError) - ValidateAndSetLicenseBytes(b []byte) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError VerifyUserEmail(userId, email string) *model.AppError ViewChannel(view *model.ChannelView, userId string, currentSessionId string) (map[string]int64, *model.AppError) diff --git a/app/app_test.go b/app/app_test.go index 0d2bbb013a..3bf8e3c624 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/mock" "github.com/mattermost/mattermost-server/v5/model" + "github.com/mattermost/mattermost-server/v5/services/searchengine/bleveengine" "github.com/mattermost/mattermost-server/v5/store/storetest/mocks" ) @@ -31,6 +32,9 @@ func TestAppRace(t *testing.T) { func TestUnitUpdateConfig(t *testing.T) { th := SetupWithStoreMock(t) defer th.TearDown() + bleveEngine := bleveengine.NewBleveEngine(th.App.Config(), th.App.Srv().Jobs) + _ = bleveEngine.Start() + th.App.Srv().SearchEngine.RegisterBleveEngine(bleveEngine) mockStore := th.App.Srv().Store.(*mocks.Store) mockUserStore := mocks.UserStore{} @@ -40,9 +44,13 @@ func TestUnitUpdateConfig(t *testing.T) { mockSystemStore := mocks.SystemStore{} mockSystemStore.On("GetByName", "InstallationDate").Return(&model.System{Name: "InstallationDate", Value: "10"}, nil) mockSystemStore.On("GetByName", "FirstServerRunTimestamp").Return(&model.System{Name: "FirstServerRunTimestamp", Value: "10"}, nil) + mockSystemStore.On("Get").Return(make(model.StringMap), nil) + mockLicenseStore := mocks.LicenseStore{} + mockLicenseStore.On("Get", "").Return(&model.LicenseRecord{}, nil) mockStore.On("User").Return(&mockUserStore) mockStore.On("Post").Return(&mockPostStore) mockStore.On("System").Return(&mockSystemStore) + mockStore.On("License").Return(&mockLicenseStore) prev := *th.App.Config().ServiceSettings.SiteURL @@ -251,7 +259,7 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictPrivateChannelManagement = model.PERMISSIONS_TEAM_ADMIN }) - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) // Check the migration doesn't change anything if run again. th.App.DoAdvancedPermissionsMigration() @@ -427,7 +435,7 @@ func TestDoAdvancedPermissionsMigration(t *testing.T) { } // Remove the license. - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) // Do the migration again. th.ResetRoleMigration() diff --git a/app/authentication.go b/app/authentication.go index 1814df9ab2..8df77f5820 100644 --- a/app/authentication.go +++ b/app/authentication.go @@ -221,7 +221,7 @@ func checkUserNotBot(user *model.User) *model.AppError { } func (a *App) authenticateUser(user *model.User, password, mfaToken string) (*model.User, *model.AppError) { - license := a.License() + license := a.Srv().License() ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap() != nil && license != nil && *license.Features.LDAP if user.AuthService == model.USER_AUTH_SERVICE_LDAP { diff --git a/app/cluster_discovery.go b/app/cluster_discovery.go index ebf9cb636c..30de725779 100644 --- a/app/cluster_discovery.go +++ b/app/cluster_discovery.go @@ -16,38 +16,42 @@ const ( type ClusterDiscoveryService struct { model.ClusterDiscovery - app *App + srv *Server stop chan bool } -func (a *App) NewClusterDiscoveryService() *ClusterDiscoveryService { +func (s *Server) NewClusterDiscoveryService() *ClusterDiscoveryService { ds := &ClusterDiscoveryService{ ClusterDiscovery: model.ClusterDiscovery{}, - app: a, + srv: s, stop: make(chan bool), } return ds } +func (a *App) NewClusterDiscoveryService() *ClusterDiscoveryService { + return a.Srv().NewClusterDiscoveryService() +} + func (me *ClusterDiscoveryService) Start() { - err := me.app.Srv().Store.ClusterDiscovery().Cleanup() + err := me.srv.Store.ClusterDiscovery().Cleanup() if err != nil { mlog.Error("ClusterDiscoveryService failed to cleanup the outdated cluster discovery information", mlog.Err(err)) } - exists, err := me.app.Srv().Store.ClusterDiscovery().Exists(&me.ClusterDiscovery) + exists, err := me.srv.Store.ClusterDiscovery().Exists(&me.ClusterDiscovery) if err != nil { mlog.Error("ClusterDiscoveryService failed to check if row exists", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) } else { if exists { - if _, err := me.app.Srv().Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil { + if _, err := me.srv.Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil { mlog.Error("ClusterDiscoveryService failed to start clean", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) } } } - if err := me.app.Srv().Store.ClusterDiscovery().Save(&me.ClusterDiscovery); err != nil { + if err := me.srv.Store.ClusterDiscovery().Save(&me.ClusterDiscovery); err != nil { mlog.Error("ClusterDiscoveryService failed to save", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) return } @@ -57,7 +61,7 @@ func (me *ClusterDiscoveryService) Start() { ticker := time.NewTicker(DISCOVERY_SERVICE_WRITE_PING) defer func() { ticker.Stop() - if _, err := me.app.Srv().Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil { + if _, err := me.srv.Store.ClusterDiscovery().Delete(&me.ClusterDiscovery); err != nil { mlog.Error("ClusterDiscoveryService failed to cleanup", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) } mlog.Debug("ClusterDiscoveryService ping writer stopped", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson())) @@ -66,7 +70,7 @@ func (me *ClusterDiscoveryService) Start() { for { select { case <-ticker.C: - if err := me.app.Srv().Store.ClusterDiscovery().SetLastPingAt(&me.ClusterDiscovery); err != nil { + if err := me.srv.Store.ClusterDiscovery().SetLastPingAt(&me.ClusterDiscovery); err != nil { mlog.Error("ClusterDiscoveryService failed to write ping", mlog.String("ClusterDiscovery", me.ClusterDiscovery.ToJson()), mlog.Err(err)) } case <-me.stop: @@ -80,13 +84,17 @@ func (me *ClusterDiscoveryService) Stop() { me.stop <- true } -func (a *App) IsLeader() bool { - if a.License() != nil && *a.Config().ClusterSettings.Enable && a.Cluster() != nil { - return a.Cluster().IsLeader() +func (s *Server) IsLeader() bool { + if s.License() != nil && *s.Config().ClusterSettings.Enable && s.Cluster != nil { + return s.Cluster.IsLeader() } return true } +func (a *App) IsLeader() bool { + return a.Srv().IsLeader() +} + func (a *App) GetClusterId() string { if a.Cluster() == nil { return "" diff --git a/app/cluster_handlers.go b/app/cluster_handlers.go index 43dba74a86..1d3a7578a2 100644 --- a/app/cluster_handlers.go +++ b/app/cluster_handlers.go @@ -43,7 +43,7 @@ func (a *App) clusterUpdateStatusHandler(msg *model.ClusterMessage) { } func (a *App) clusterInvalidateAllCachesHandler(msg *model.ClusterMessage) { - a.InvalidateAllCachesSkipSend() + a.Srv().InvalidateAllCachesSkipSend() } func (a *App) clusterInvalidateCacheForChannelMembersNotifyPropHandler(msg *model.ClusterMessage) { diff --git a/app/compliance.go b/app/compliance.go index 5ec6ed1e7c..e4113a4eec 100644 --- a/app/compliance.go +++ b/app/compliance.go @@ -12,7 +12,7 @@ import ( ) func (a *App) GetComplianceReports(page, perPage int) (model.Compliances, *model.AppError) { - if license := a.License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance { + if license := a.Srv().License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance { return nil, model.NewAppError("GetComplianceReports", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } @@ -20,7 +20,7 @@ func (a *App) GetComplianceReports(page, perPage int) (model.Compliances, *model } func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError) { - if license := a.License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance() == nil { + if license := a.Srv().License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance() == nil { return nil, model.NewAppError("saveComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } @@ -39,7 +39,7 @@ func (a *App) SaveComplianceReport(job *model.Compliance) (*model.Compliance, *m } func (a *App) GetComplianceReport(reportId string) (*model.Compliance, *model.AppError) { - if license := a.License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance() == nil { + if license := a.Srv().License(); !*a.Config().ComplianceSettings.Enable || license == nil || !*license.Features.Compliance || a.Compliance() == nil { return nil, model.NewAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "", http.StatusNotImplemented) } diff --git a/app/config.go b/app/config.go index 1d4c9edc01..e5edfe6997 100644 --- a/app/config.go +++ b/app/config.go @@ -76,7 +76,7 @@ func (a *App) ClientConfig() map[string]string { } func (a *App) ClientConfigHash() string { - return a.Srv().clientConfigHash.Load().(string) + return a.Srv().ClientConfigHash() } func (a *App) LimitedClientConfig() map[string]string { @@ -106,14 +106,14 @@ func (a *App) RemoveConfigListener(id string) { // ensurePostActionCookieSecret ensures that the key for encrypting PostActionCookie exists // and future calls to PostActionCookieSecret will always return a valid key, same on all // servers in the cluster -func (a *App) ensurePostActionCookieSecret() error { - if a.Srv().postActionCookieSecret != nil { +func (s *Server) ensurePostActionCookieSecret() error { + if s.postActionCookieSecret != nil { return nil } var secret *model.SystemPostActionCookieSecret - value, err := a.Srv().Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) + value, err := s.Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) if err == nil { if err := json.Unmarshal([]byte(value.Value), &secret); err != nil { return err @@ -139,7 +139,7 @@ func (a *App) ensurePostActionCookieSecret() error { } system.Value = string(v) // If we were able to save the key, use it, otherwise log the error. - if appErr := a.Srv().Store.System().Save(system); appErr != nil { + if appErr := s.Store.System().Save(system); appErr != nil { mlog.Error("Failed to save PostActionCookieSecret", mlog.Err(appErr)) } else { secret = newSecret @@ -149,7 +149,7 @@ func (a *App) ensurePostActionCookieSecret() error { // If we weren't able to save a new key above, another server must have beat us to it. Get the // key from the database, and if that fails, error out. if secret == nil { - value, err := a.Srv().Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) + value, err := s.Store.System().GetByName(model.SYSTEM_POST_ACTION_COOKIE_SECRET) if err != nil { return err } @@ -159,20 +159,20 @@ func (a *App) ensurePostActionCookieSecret() error { } } - a.Srv().postActionCookieSecret = secret.Secret + s.postActionCookieSecret = secret.Secret return nil } -// EnsureAsymmetricSigningKey ensures that an asymmetric signing key exists and future calls to +// ensureAsymmetricSigningKey ensures that an asymmetric signing key exists and future calls to // AsymmetricSigningKey will always return a valid signing key. -func (a *App) ensureAsymmetricSigningKey() error { - if a.Srv().asymmetricSigningKey != nil { +func (s *Server) ensureAsymmetricSigningKey() error { + if s.asymmetricSigningKey != nil { return nil } var key *model.SystemAsymmetricSigningKey - value, err := a.Srv().Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) + value, err := s.Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) if err == nil { if err := json.Unmarshal([]byte(value.Value), &key); err != nil { return err @@ -202,7 +202,7 @@ func (a *App) ensureAsymmetricSigningKey() error { } system.Value = string(v) // If we were able to save the key, use it, otherwise log the error. - if appErr := a.Srv().Store.System().Save(system); appErr != nil { + if appErr := s.Store.System().Save(system); appErr != nil { mlog.Error("Failed to save AsymmetricSigningKey", mlog.Err(appErr)) } else { key = newKey @@ -212,7 +212,7 @@ func (a *App) ensureAsymmetricSigningKey() error { // If we weren't able to save a new key above, another server must have beat us to it. Get the // key from the database, and if that fails, error out. if key == nil { - value, err := a.Srv().Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) + value, err := s.Store.System().GetByName(model.SYSTEM_ASYMMETRIC_SIGNING_KEY) if err != nil { return err } @@ -229,7 +229,7 @@ func (a *App) ensureAsymmetricSigningKey() error { default: return fmt.Errorf("unknown curve: " + key.ECDSAKey.Curve) } - a.Srv().asymmetricSigningKey = &ecdsa.PrivateKey{ + s.asymmetricSigningKey = &ecdsa.PrivateKey{ PublicKey: ecdsa.PublicKey{ Curve: curve, X: key.ECDSAKey.X, @@ -237,17 +237,17 @@ func (a *App) ensureAsymmetricSigningKey() error { }, D: key.ECDSAKey.D, } - a.regenerateClientConfig() + s.regenerateClientConfig() return nil } -func (a *App) ensureInstallationDate() error { - _, err := a.getSystemInstallDate() +func (s *Server) ensureInstallationDate() error { + _, err := s.getSystemInstallDate() if err == nil { return nil } - installDate, err := a.Srv().Store.User().InferSystemInstallDate() + installDate, err := s.Store.User().InferSystemInstallDate() var installationDate int64 if err == nil && installDate > 0 { installationDate = installDate @@ -255,7 +255,7 @@ func (a *App) ensureInstallationDate() error { installationDate = utils.MillisFromTime(time.Now()) } - err = a.Srv().Store.System().SaveOrUpdate(&model.System{ + err = s.Store.System().SaveOrUpdate(&model.System{ Name: model.SYSTEM_INSTALLATION_DATE_KEY, Value: strconv.FormatInt(installationDate, 10), }) @@ -265,13 +265,13 @@ func (a *App) ensureInstallationDate() error { return nil } -func (a *App) ensureFirstServerRunTimestamp() error { - _, err := a.getFirstServerRunTimestamp() +func (s *Server) ensureFirstServerRunTimestamp() error { + _, err := s.getFirstServerRunTimestamp() if err == nil { return nil } - err = a.Srv().Store.System().SaveOrUpdate(&model.System{ + err = s.Store.System().SaveOrUpdate(&model.System{ Name: model.SYSTEM_FIRST_SERVER_RUN_TIMESTAMP_KEY, Value: strconv.FormatInt(utils.MillisFromTime(time.Now()), 10), }) @@ -298,12 +298,12 @@ func (a *App) PostActionCookieSecret() []byte { return a.Srv().PostActionCookieSecret() } -func (a *App) regenerateClientConfig() { - clientConfig := config.GenerateClientConfig(a.Config(), a.DiagnosticId(), a.License()) - limitedClientConfig := config.GenerateLimitedClientConfig(a.Config(), a.DiagnosticId(), a.License()) +func (s *Server) regenerateClientConfig() { + clientConfig := config.GenerateClientConfig(s.Config(), s.diagnosticId, s.License()) + limitedClientConfig := config.GenerateLimitedClientConfig(s.Config(), s.diagnosticId, s.License()) if clientConfig["EnableCustomTermsOfService"] == "true" { - termsOfService, err := a.GetLatestTermsOfService() + termsOfService, err := s.Store.TermsOfService().GetLatest(true) if err != nil { mlog.Err(err) } else { @@ -312,16 +312,16 @@ func (a *App) regenerateClientConfig() { } } - if key := a.AsymmetricSigningKey(); key != nil { + if key := s.AsymmetricSigningKey(); key != nil { der, _ := x509.MarshalPKIXPublicKey(&key.PublicKey) clientConfig["AsymmetricSigningPublicKey"] = base64.StdEncoding.EncodeToString(der) limitedClientConfig["AsymmetricSigningPublicKey"] = base64.StdEncoding.EncodeToString(der) } clientConfigJSON, _ := json.Marshal(clientConfig) - a.Srv().clientConfig.Store(clientConfig) - a.Srv().limitedClientConfig.Store(limitedClientConfig) - a.Srv().clientConfigHash.Store(fmt.Sprintf("%x", md5.Sum(clientConfigJSON))) + s.clientConfig.Store(clientConfig) + s.limitedClientConfig.Store(limitedClientConfig) + s.clientConfigHash.Store(fmt.Sprintf("%x", md5.Sum(clientConfigJSON))) } func (a *App) GetCookieDomain() string { @@ -338,24 +338,29 @@ func (a *App) GetSiteURL() string { } // ClientConfigWithComputed gets the configuration in a format suitable for sending to the client. -func (a *App) ClientConfigWithComputed() map[string]string { +func (s *Server) ClientConfigWithComputed() map[string]string { respCfg := map[string]string{} - for k, v := range a.ClientConfig() { + for k, v := range s.clientConfig.Load().(map[string]string) { respCfg[k] = v } // These properties are not configurable, but nevertheless represent configuration expected // by the client. - respCfg["NoAccounts"] = strconv.FormatBool(a.IsFirstUserAccount()) - respCfg["MaxPostSize"] = strconv.Itoa(a.MaxPostSize()) + respCfg["NoAccounts"] = strconv.FormatBool(s.IsFirstUserAccount()) + respCfg["MaxPostSize"] = strconv.Itoa(s.MaxPostSize()) respCfg["InstallationDate"] = "" - if installationDate, err := a.getSystemInstallDate(); err == nil { + if installationDate, err := s.getSystemInstallDate(); err == nil { respCfg["InstallationDate"] = strconv.FormatInt(installationDate, 10) } return respCfg } +// ClientConfigWithComputed gets the configuration in a format suitable for sending to the client. +func (a *App) ClientConfigWithComputed() map[string]string { + return a.Srv().ClientConfigWithComputed() +} + // LimitedClientConfigWithComputed gets the configuration in a format suitable for sending to the client. func (a *App) LimitedClientConfigWithComputed() map[string]string { respCfg := map[string]string{} @@ -394,26 +399,26 @@ func (a *App) GetEnvironmentConfig() map[string]interface{} { } // SaveConfig replaces the active configuration, optionally notifying cluster peers. -func (a *App) SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bool) *model.AppError { - oldCfg, err := a.Srv().configStore.Set(newCfg) +func (s *Server) SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bool) *model.AppError { + oldCfg, err := s.configStore.Set(newCfg) if errors.Cause(err) == config.ErrReadOnlyConfiguration { return model.NewAppError("saveConfig", "ent.cluster.save_config.error", nil, err.Error(), http.StatusForbidden) } else if err != nil { return model.NewAppError("saveConfig", "app.save_config.app_error", nil, err.Error(), http.StatusInternalServerError) } - if a.Metrics() != nil { - if *a.Config().MetricsSettings.Enable { - a.Metrics().StartServer() + if s.Metrics != nil { + if *s.Config().MetricsSettings.Enable { + s.Metrics.StartServer() } else { - a.Metrics().StopServer() + s.Metrics.StopServer() } } - if a.Cluster() != nil { - newCfg = a.Srv().configStore.RemoveEnvironmentOverrides(newCfg) - oldCfg = a.Srv().configStore.RemoveEnvironmentOverrides(oldCfg) - err := a.Cluster().ConfigChanged(oldCfg, newCfg, sendConfigChangeClusterMessage) + if s.Cluster != nil { + newCfg = s.configStore.RemoveEnvironmentOverrides(newCfg) + oldCfg = s.configStore.RemoveEnvironmentOverrides(oldCfg) + err := s.Cluster.ConfigChanged(oldCfg, newCfg, sendConfigChangeClusterMessage) if err != nil { return err } @@ -422,6 +427,11 @@ func (a *App) SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bo return nil } +// SaveConfig replaces the active configuration, optionally notifying cluster peers. +func (a *App) SaveConfig(newCfg *model.Config, sendConfigChangeClusterMessage bool) *model.AppError { + return a.Srv().SaveConfig(newCfg, sendConfigChangeClusterMessage) +} + func (a *App) HandleMessageExportConfig(cfg *model.Config, appCfg *model.Config) { // If the Message Export feature has been toggled in the System Console, rewrite the ExportFromTimestamp field to an // appropriate value. The rewriting occurs here to ensure it doesn't affect values written to the config file diff --git a/app/config_test.go b/app/config_test.go index fe59c4c2d4..b6747f327a 100644 --- a/app/config_test.go +++ b/app/config_test.go @@ -142,7 +142,7 @@ func TestEnsureInstallationDate(t *testing.T) { }) } - err := th.App.ensureInstallationDate() + err := th.App.Srv().ensureInstallationDate() if tc.ExpectedInstallationDate == nil { assert.Error(t, err) diff --git a/app/diagnostics.go b/app/diagnostics.go index 764cd73519..fda944ac2c 100644 --- a/app/diagnostics.go +++ b/app/diagnostics.go @@ -70,51 +70,51 @@ const ( // declaring this as var to allow overriding in tests var SENTRY_DSN = "placeholder_sentry_dsn" -func (a *App) SendDailyDiagnostics() { - a.sendDailyDiagnostics(false) +func (s *Server) SendDailyDiagnostics() { + s.sendDailyDiagnostics(false) } -func (a *App) sendDailyDiagnostics(override bool) { - if *a.Config().LogSettings.EnableDiagnostics && a.IsLeader() && (!strings.Contains(SEGMENT_KEY, "placeholder") || override) { - a.Srv().initDiagnostics("") - a.trackActivity() - a.trackConfig() - a.trackLicense() - a.trackPlugins() - a.trackServer() - a.trackPermissions() - a.trackElasticsearch() - a.trackGroups() - a.trackChannelModeration() +func (s *Server) sendDailyDiagnostics(override bool) { + if *s.Config().LogSettings.EnableDiagnostics && s.IsLeader() && (!strings.Contains(SEGMENT_KEY, "placeholder") || override) { + s.initDiagnostics("") + s.trackActivity() + s.trackConfig() + s.trackLicense() + s.trackPlugins() + s.trackServer() + s.trackPermissions() + s.trackElasticsearch() + s.trackGroups() + s.trackChannelModeration() } - if *a.Config().LogSettings.EnableDiagnostics && a.IsLeader() && ((!strings.Contains(RUDDER_KEY, "placeholder") && !strings.Contains(RUDDER_DATAPLANE_URL, "placeholder")) || override) { - a.Srv().initRudder(RUDDER_DATAPLANE_URL) - a.trackActivity() - a.trackConfig() - a.trackLicense() - a.trackPlugins() - a.trackServer() - a.trackPermissions() - a.trackElasticsearch() - a.trackGroups() - a.trackChannelModeration() + if *s.Config().LogSettings.EnableDiagnostics && s.IsLeader() && ((!strings.Contains(RUDDER_KEY, "placeholder") && !strings.Contains(RUDDER_DATAPLANE_URL, "placeholder")) || override) { + s.initRudder(RUDDER_DATAPLANE_URL) + s.trackActivity() + s.trackConfig() + s.trackLicense() + s.trackPlugins() + s.trackServer() + s.trackPermissions() + s.trackElasticsearch() + s.trackGroups() + s.trackChannelModeration() } } -func (a *App) SendDiagnostic(event string, properties map[string]interface{}) { - if a.Srv().diagnosticClient != nil { - a.Srv().diagnosticClient.Enqueue(analytics.Track{ +func (s *Server) SendDiagnostic(event string, properties map[string]interface{}) { + if s.diagnosticClient != nil { + s.diagnosticClient.Enqueue(analytics.Track{ Event: event, - UserId: a.DiagnosticId(), + UserId: s.diagnosticId, Properties: properties, }) } - if a.Srv().rudderClient != nil { - a.Srv().rudderClient.Enqueue(rudder.Track{ + if s.rudderClient != nil { + s.rudderClient.Enqueue(rudder.Track{ Event: event, - UserId: a.DiagnosticId(), + UserId: s.diagnosticId, Properties: properties, }) } @@ -152,7 +152,7 @@ func pluginVersion(pluginsAvailable []*model.BundleInfo, pluginId string) string return "" } -func (a *App) trackActivity() { +func (s *Server) trackActivity() { var userCount int64 var guestAccountsCount int64 var botAccountsCount int64 @@ -171,82 +171,82 @@ func (a *App) trackActivity() { activeUsersDailyCountChan := make(chan store.StoreResult, 1) go func() { - count, err := a.Srv().Store.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) + count, err := s.Store.User().AnalyticsActiveCount(DAY_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) activeUsersDailyCountChan <- store.StoreResult{Data: count, Err: err} close(activeUsersDailyCountChan) }() activeUsersMonthlyCountChan := make(chan store.StoreResult, 1) go func() { - count, err := a.Srv().Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) + count, err := s.Store.User().AnalyticsActiveCount(MONTH_MILLISECONDS, model.UserCountOptions{IncludeBotAccounts: false, IncludeDeleted: false}) activeUsersMonthlyCountChan <- store.StoreResult{Data: count, Err: err} close(activeUsersMonthlyCountChan) }() - if count, err := a.Srv().Store.User().Count(model.UserCountOptions{IncludeDeleted: true}); err == nil { + if count, err := s.Store.User().Count(model.UserCountOptions{IncludeDeleted: true}); err == nil { userCount = count } - if count, err := a.Srv().Store.User().AnalyticsGetGuestCount(); err == nil { + if count, err := s.Store.User().AnalyticsGetGuestCount(); err == nil { guestAccountsCount = count } - if count, err := a.Srv().Store.User().Count(model.UserCountOptions{IncludeBotAccounts: true, ExcludeRegularUsers: true}); err == nil { + if count, err := s.Store.User().Count(model.UserCountOptions{IncludeBotAccounts: true, ExcludeRegularUsers: true}); err == nil { botAccountsCount = count } - if iucr, err := a.Srv().Store.User().AnalyticsGetInactiveUsersCount(); err == nil { + if iucr, err := s.Store.User().AnalyticsGetInactiveUsersCount(); err == nil { inactiveUserCount = iucr } - teamCount, err := a.Srv().Store.Team().AnalyticsTeamCount(false) + teamCount, err := s.Store.Team().AnalyticsTeamCount(false) if err != nil { mlog.Error(err.Error()) } - if ucc, err := a.Srv().Store.Channel().AnalyticsTypeCount("", "O"); err == nil { + if ucc, err := s.Store.Channel().AnalyticsTypeCount("", "O"); err == nil { publicChannelCount = ucc } - if pcc, err := a.Srv().Store.Channel().AnalyticsTypeCount("", "P"); err == nil { + if pcc, err := s.Store.Channel().AnalyticsTypeCount("", "P"); err == nil { privateChannelCount = pcc } - if dcc, err := a.Srv().Store.Channel().AnalyticsTypeCount("", "D"); err == nil { + if dcc, err := s.Store.Channel().AnalyticsTypeCount("", "D"); err == nil { directChannelCount = dcc } - if duccr, err := a.Srv().Store.Channel().AnalyticsDeletedTypeCount("", "O"); err == nil { + if duccr, err := s.Store.Channel().AnalyticsDeletedTypeCount("", "O"); err == nil { deletedPublicChannelCount = duccr } - if dpccr, err := a.Srv().Store.Channel().AnalyticsDeletedTypeCount("", "P"); err == nil { + if dpccr, err := s.Store.Channel().AnalyticsDeletedTypeCount("", "P"); err == nil { deletedPrivateChannelCount = dpccr } - postsCount, _ = a.Srv().Store.Post().AnalyticsPostCount("", false, false) + postsCount, _ = s.Store.Post().AnalyticsPostCount("", false, false) postCountsOptions := &model.AnalyticsPostCountsOptions{TeamId: "", BotsOnly: false, YesterdayOnly: true} - postCountsYesterday, _ := a.Srv().Store.Post().AnalyticsPostCountsByDay(postCountsOptions) + postCountsYesterday, _ := s.Store.Post().AnalyticsPostCountsByDay(postCountsOptions) postsCountPreviousDay = 0 if len(postCountsYesterday) > 0 { postsCountPreviousDay = int64(postCountsYesterday[0].Value) } postCountsOptions = &model.AnalyticsPostCountsOptions{TeamId: "", BotsOnly: true, YesterdayOnly: true} - botPostCountsYesterday, _ := a.Srv().Store.Post().AnalyticsPostCountsByDay(postCountsOptions) + botPostCountsYesterday, _ := s.Store.Post().AnalyticsPostCountsByDay(postCountsOptions) botPostsCountPreviousDay = 0 if len(botPostCountsYesterday) > 0 { botPostsCountPreviousDay = int64(botPostCountsYesterday[0].Value) } - slashCommandsCount, _ = a.Srv().Store.Command().AnalyticsCommandCount("") + slashCommandsCount, _ = s.Store.Command().AnalyticsCommandCount("") - if c, err := a.Srv().Store.Webhook().AnalyticsIncomingCount(""); err == nil { + if c, err := s.Store.Webhook().AnalyticsIncomingCount(""); err == nil { incomingWebhooksCount = c } - outgoingWebhooksCount, _ = a.Srv().Store.Webhook().AnalyticsOutgoingCount("") + outgoingWebhooksCount, _ = s.Store.Webhook().AnalyticsOutgoingCount("") var activeUsersDailyCount int64 if r := <-activeUsersDailyCountChan; r.Err == nil { @@ -258,7 +258,7 @@ func (a *App) trackActivity() { activeUsersMonthlyCount = r.Data.(int64) } - a.SendDiagnostic(TRACK_ACTIVITY, map[string]interface{}{ + s.SendDiagnostic(TRACK_ACTIVITY, map[string]interface{}{ "registered_users": userCount, "bot_accounts": botAccountsCount, "guest_accounts": guestAccountsCount, @@ -280,9 +280,9 @@ func (a *App) trackActivity() { }) } -func (a *App) trackConfig() { - cfg := a.Config() - a.SendDiagnostic(TRACK_CONFIG_SERVICE, map[string]interface{}{ +func (s *Server) trackConfig() { + cfg := s.Config() + s.SendDiagnostic(TRACK_CONFIG_SERVICE, map[string]interface{}{ "web_server_mode": *cfg.ServiceSettings.WebserverMode, "enable_security_fix_alert": *cfg.ServiceSettings.EnableSecurityFixAlert, "enable_insecure_outgoing_connections": *cfg.ServiceSettings.EnableInsecureOutgoingConnections, @@ -361,7 +361,7 @@ func (a *App) trackConfig() { "enable_local_mode": *cfg.ServiceSettings.EnableLocalMode, }) - a.SendDiagnostic(TRACK_CONFIG_TEAM, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_TEAM, map[string]interface{}{ "enable_user_creation": cfg.TeamSettings.EnableUserCreation, "enable_team_creation": *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_EnableTeamCreation, "restrict_team_invite": *cfg.TeamSettings.DEPRECATED_DO_NOT_USE_RestrictTeamInvite, @@ -395,7 +395,7 @@ func (a *App) trackConfig() { "experimental_default_channels": len(cfg.TeamSettings.ExperimentalDefaultChannels), }) - a.SendDiagnostic(TRACK_CONFIG_CLIENT_REQ, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_CLIENT_REQ, map[string]interface{}{ "android_latest_version": cfg.ClientRequirements.AndroidLatestVersion, "android_min_version": cfg.ClientRequirements.AndroidMinVersion, "desktop_latest_version": cfg.ClientRequirements.DesktopLatestVersion, @@ -404,7 +404,7 @@ func (a *App) trackConfig() { "ios_min_version": cfg.ClientRequirements.IosMinVersion, }) - a.SendDiagnostic(TRACK_CONFIG_SQL, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_SQL, map[string]interface{}{ "driver_name": *cfg.SqlSettings.DriverName, "trace": cfg.SqlSettings.Trace, "max_idle_conns": *cfg.SqlSettings.MaxIdleConns, @@ -416,7 +416,7 @@ func (a *App) trackConfig() { "disable_database_search": *cfg.SqlSettings.DisableDatabaseSearch, }) - a.SendDiagnostic(TRACK_CONFIG_LOG, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_LOG, map[string]interface{}{ "enable_console": cfg.LogSettings.EnableConsole, "console_level": cfg.LogSettings.ConsoleLevel, "console_json": *cfg.LogSettings.ConsoleJson, @@ -427,7 +427,7 @@ func (a *App) trackConfig() { "isdefault_file_location": isDefault(cfg.LogSettings.FileLocation, ""), }) - a.SendDiagnostic(TRACK_CONFIG_AUDIT, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_AUDIT, map[string]interface{}{ "syslog_enabled": *cfg.ExperimentalAuditSettings.SysLogEnabled, "syslog_insecure": *cfg.ExperimentalAuditSettings.SysLogInsecure, "syslog_max_queue_size": *cfg.ExperimentalAuditSettings.SysLogMaxQueueSize, @@ -439,7 +439,7 @@ func (a *App) trackConfig() { "file_max_queue_size": *cfg.ExperimentalAuditSettings.FileMaxQueueSize, }) - a.SendDiagnostic(TRACK_CONFIG_NOTIFICATION_LOG, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_NOTIFICATION_LOG, map[string]interface{}{ "enable_console": *cfg.NotificationLogSettings.EnableConsole, "console_level": *cfg.NotificationLogSettings.ConsoleLevel, "console_json": *cfg.NotificationLogSettings.ConsoleJson, @@ -449,7 +449,7 @@ func (a *App) trackConfig() { "isdefault_file_location": isDefault(*cfg.NotificationLogSettings.FileLocation, ""), }) - a.SendDiagnostic(TRACK_CONFIG_PASSWORD, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_PASSWORD, map[string]interface{}{ "minimum_length": *cfg.PasswordSettings.MinimumLength, "lowercase": *cfg.PasswordSettings.Lowercase, "number": *cfg.PasswordSettings.Number, @@ -457,7 +457,7 @@ func (a *App) trackConfig() { "symbol": *cfg.PasswordSettings.Symbol, }) - a.SendDiagnostic(TRACK_CONFIG_FILE, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_FILE, map[string]interface{}{ "enable_public_links": cfg.FileSettings.EnablePublicLink, "driver_name": *cfg.FileSettings.DriverName, "isdefault_directory": isDefault(*cfg.FileSettings.Directory, model.FILE_SETTINGS_DEFAULT_DIRECTORY), @@ -472,7 +472,7 @@ func (a *App) trackConfig() { "enable_mobile_download": *cfg.FileSettings.EnableMobileDownload, }) - a.SendDiagnostic(TRACK_CONFIG_EMAIL, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_EMAIL, map[string]interface{}{ "enable_sign_up_with_email": cfg.EmailSettings.EnableSignUpWithEmail, "enable_sign_in_with_email": *cfg.EmailSettings.EnableSignInWithEmail, "enable_sign_in_with_username": *cfg.EmailSettings.EnableSignInWithUsername, @@ -499,7 +499,7 @@ func (a *App) trackConfig() { "smtp_server_timeout": *cfg.EmailSettings.SMTPServerTimeout, }) - a.SendDiagnostic(TRACK_CONFIG_RATE, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_RATE, map[string]interface{}{ "enable_rate_limiter": *cfg.RateLimitSettings.Enable, "vary_by_remote_address": *cfg.RateLimitSettings.VaryByRemoteAddr, "vary_by_user": *cfg.RateLimitSettings.VaryByUser, @@ -509,25 +509,25 @@ func (a *App) trackConfig() { "isdefault_vary_by_header": isDefault(cfg.RateLimitSettings.VaryByHeader, ""), }) - a.SendDiagnostic(TRACK_CONFIG_PRIVACY, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_PRIVACY, map[string]interface{}{ "show_email_address": cfg.PrivacySettings.ShowEmailAddress, "show_full_name": cfg.PrivacySettings.ShowFullName, }) - a.SendDiagnostic(TRACK_CONFIG_THEME, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_THEME, map[string]interface{}{ "enable_theme_selection": *cfg.ThemeSettings.EnableThemeSelection, "isdefault_default_theme": isDefault(*cfg.ThemeSettings.DefaultTheme, model.TEAM_SETTINGS_DEFAULT_TEAM_TEXT), "allow_custom_themes": *cfg.ThemeSettings.AllowCustomThemes, "allowed_themes": len(cfg.ThemeSettings.AllowedThemes), }) - a.SendDiagnostic(TRACK_CONFIG_OAUTH, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_OAUTH, map[string]interface{}{ "enable_gitlab": cfg.GitLabSettings.Enable, "enable_google": cfg.GoogleSettings.Enable, "enable_office365": cfg.Office365Settings.Enable, }) - a.SendDiagnostic(TRACK_CONFIG_SUPPORT, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_SUPPORT, map[string]interface{}{ "isdefault_terms_of_service_link": isDefault(*cfg.SupportSettings.TermsOfServiceLink, model.SUPPORT_SETTINGS_DEFAULT_TERMS_OF_SERVICE_LINK), "isdefault_privacy_policy_link": isDefault(*cfg.SupportSettings.PrivacyPolicyLink, model.SUPPORT_SETTINGS_DEFAULT_PRIVACY_POLICY_LINK), "isdefault_about_link": isDefault(*cfg.SupportSettings.AboutLink, model.SUPPORT_SETTINGS_DEFAULT_ABOUT_LINK), @@ -538,7 +538,7 @@ func (a *App) trackConfig() { "custom_terms_of_service_re_acceptance_period": *cfg.SupportSettings.CustomTermsOfServiceReAcceptancePeriod, }) - a.SendDiagnostic(TRACK_CONFIG_LDAP, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_LDAP, map[string]interface{}{ "enable": *cfg.LdapSettings.Enable, "enable_sync": *cfg.LdapSettings.EnableSync, "enable_admin_filter": *cfg.LdapSettings.EnableAdminFilter, @@ -567,18 +567,18 @@ func (a *App) trackConfig() { "isnotempty_picture_attribute": !isDefault(*cfg.LdapSettings.PictureAttribute, ""), }) - a.SendDiagnostic(TRACK_CONFIG_COMPLIANCE, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_COMPLIANCE, map[string]interface{}{ "enable": *cfg.ComplianceSettings.Enable, "enable_daily": *cfg.ComplianceSettings.EnableDaily, }) - a.SendDiagnostic(TRACK_CONFIG_LOCALIZATION, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_LOCALIZATION, map[string]interface{}{ "default_server_locale": *cfg.LocalizationSettings.DefaultServerLocale, "default_client_locale": *cfg.LocalizationSettings.DefaultClientLocale, "available_locales": *cfg.LocalizationSettings.AvailableLocales, }) - a.SendDiagnostic(TRACK_CONFIG_SAML, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_SAML, map[string]interface{}{ "enable": *cfg.SamlSettings.Enable, "enable_sync_with_ldap": *cfg.SamlSettings.EnableSyncWithLdap, "enable_sync_with_ldap_include_auth": *cfg.SamlSettings.EnableSyncWithLdapIncludeAuth, @@ -606,7 +606,7 @@ func (a *App) trackConfig() { "isdefault_login_button_text_color": isDefault(*cfg.SamlSettings.LoginButtonTextColor, ""), }) - a.SendDiagnostic(TRACK_CONFIG_CLUSTER, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_CLUSTER, map[string]interface{}{ "enable": *cfg.ClusterSettings.Enable, "network_interface": isDefault(*cfg.ClusterSettings.NetworkInterface, ""), "bind_address": isDefault(*cfg.ClusterSettings.BindAddress, ""), @@ -616,18 +616,18 @@ func (a *App) trackConfig() { "read_only_config": *cfg.ClusterSettings.ReadOnlyConfig, }) - a.SendDiagnostic(TRACK_CONFIG_METRICS, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_METRICS, map[string]interface{}{ "enable": *cfg.MetricsSettings.Enable, "block_profile_rate": *cfg.MetricsSettings.BlockProfileRate, }) - a.SendDiagnostic(TRACK_CONFIG_NATIVEAPP, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_NATIVEAPP, map[string]interface{}{ "isdefault_app_download_link": isDefault(*cfg.NativeAppSettings.AppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_APP_DOWNLOAD_LINK), "isdefault_android_app_download_link": isDefault(*cfg.NativeAppSettings.AndroidAppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_ANDROID_APP_DOWNLOAD_LINK), "isdefault_iosapp_download_link": isDefault(*cfg.NativeAppSettings.IosAppDownloadLink, model.NATIVEAPP_SETTINGS_DEFAULT_IOS_APP_DOWNLOAD_LINK), }) - a.SendDiagnostic(TRACK_CONFIG_EXPERIMENTAL, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_EXPERIMENTAL, map[string]interface{}{ "client_side_cert_enable": *cfg.ExperimentalSettings.ClientSideCertEnable, "isdefault_client_side_cert_check": isDefault(*cfg.ExperimentalSettings.ClientSideCertCheck, model.CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH), "link_metadata_timeout_milliseconds": *cfg.ExperimentalSettings.LinkMetadataTimeoutMilliseconds, @@ -636,18 +636,18 @@ func (a *App) trackConfig() { "use_new_saml_library": *cfg.ExperimentalSettings.UseNewSAMLLibrary, }) - a.SendDiagnostic(TRACK_CONFIG_ANALYTICS, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_ANALYTICS, map[string]interface{}{ "isdefault_max_users_for_statistics": isDefault(*cfg.AnalyticsSettings.MaxUsersForStatistics, model.ANALYTICS_SETTINGS_DEFAULT_MAX_USERS_FOR_STATISTICS), }) - a.SendDiagnostic(TRACK_CONFIG_ANNOUNCEMENT, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_ANNOUNCEMENT, map[string]interface{}{ "enable_banner": *cfg.AnnouncementSettings.EnableBanner, "isdefault_banner_color": isDefault(*cfg.AnnouncementSettings.BannerColor, model.ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_COLOR), "isdefault_banner_text_color": isDefault(*cfg.AnnouncementSettings.BannerTextColor, model.ANNOUNCEMENT_SETTINGS_DEFAULT_BANNER_TEXT_COLOR), "allow_banner_dismissal": *cfg.AnnouncementSettings.AllowBannerDismissal, }) - a.SendDiagnostic(TRACK_CONFIG_ELASTICSEARCH, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_ELASTICSEARCH, map[string]interface{}{ "isdefault_connection_url": isDefault(*cfg.ElasticsearchSettings.ConnectionUrl, model.ELASTICSEARCH_SETTINGS_DEFAULT_CONNECTION_URL), "isdefault_username": isDefault(*cfg.ElasticsearchSettings.Username, model.ELASTICSEARCH_SETTINGS_DEFAULT_USERNAME), "isdefault_password": isDefault(*cfg.ElasticsearchSettings.Password, model.ELASTICSEARCH_SETTINGS_DEFAULT_PASSWORD), @@ -700,7 +700,7 @@ func (a *App) trackConfig() { "signature_public_key_files": len(cfg.PluginSettings.SignaturePublicKeyFiles), } - pluginsEnvironment := a.GetPluginsEnvironment() + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment != nil { if plugins, appErr := pluginsEnvironment.Available(); appErr != nil { mlog.Error("Unable to add plugin versions to diagnostics", mlog.Err(appErr)) @@ -720,9 +720,9 @@ func (a *App) trackConfig() { } } - a.SendDiagnostic(TRACK_CONFIG_PLUGIN, pluginConfigData) + s.SendDiagnostic(TRACK_CONFIG_PLUGIN, pluginConfigData) - a.SendDiagnostic(TRACK_CONFIG_DATA_RETENTION, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_DATA_RETENTION, map[string]interface{}{ "enable_message_deletion": *cfg.DataRetentionSettings.EnableMessageDeletion, "enable_file_deletion": *cfg.DataRetentionSettings.EnableFileDeletion, "message_retention_days": *cfg.DataRetentionSettings.MessageRetentionDays, @@ -730,7 +730,7 @@ func (a *App) trackConfig() { "deletion_job_start_time": *cfg.DataRetentionSettings.DeletionJobStartTime, }) - a.SendDiagnostic(TRACK_CONFIG_MESSAGE_EXPORT, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_MESSAGE_EXPORT, map[string]interface{}{ "enable_message_export": *cfg.MessageExportSettings.EnableExport, "export_format": *cfg.MessageExportSettings.ExportFormat, "daily_run_time": *cfg.MessageExportSettings.DailyRunTime, @@ -742,26 +742,26 @@ func (a *App) trackConfig() { "is_default_global_relay_email_address": isDefault(*cfg.MessageExportSettings.GlobalRelaySettings.EmailAddress, ""), }) - a.SendDiagnostic(TRACK_CONFIG_DISPLAY, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_DISPLAY, map[string]interface{}{ "experimental_timezone": *cfg.DisplaySettings.ExperimentalTimezone, "isdefault_custom_url_schemes": len(cfg.DisplaySettings.CustomUrlSchemes) != 0, }) - a.SendDiagnostic(TRACK_CONFIG_GUEST_ACCOUNTS, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_GUEST_ACCOUNTS, map[string]interface{}{ "enable": *cfg.GuestAccountsSettings.Enable, "allow_email_accounts": *cfg.GuestAccountsSettings.AllowEmailAccounts, "enforce_multifactor_authentication": *cfg.GuestAccountsSettings.EnforceMultifactorAuthentication, "isdefault_restrict_creation_to_domains": isDefault(*cfg.GuestAccountsSettings.RestrictCreationToDomains, ""), }) - a.SendDiagnostic(TRACK_CONFIG_IMAGE_PROXY, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_IMAGE_PROXY, map[string]interface{}{ "enable": *cfg.ImageProxySettings.Enable, "image_proxy_type": *cfg.ImageProxySettings.ImageProxyType, "isdefault_remote_image_proxy_url": isDefault(*cfg.ImageProxySettings.RemoteImageProxyURL, ""), "isdefault_remote_image_proxy_options": isDefault(*cfg.ImageProxySettings.RemoteImageProxyOptions, ""), }) - a.SendDiagnostic(TRACK_CONFIG_BLEVE, map[string]interface{}{ + s.SendDiagnostic(TRACK_CONFIG_BLEVE, map[string]interface{}{ "enable_indexing": *cfg.BleveSettings.EnableIndexing, "enable_searching": *cfg.BleveSettings.EnableSearching, "enable_autocomplete": *cfg.BleveSettings.EnableAutocomplete, @@ -769,8 +769,8 @@ func (a *App) trackConfig() { }) } -func (a *App) trackLicense() { - if license := a.License(); license != nil { +func (s *Server) trackLicense() { + if license := s.License(); license != nil { data := map[string]interface{}{ "customer_id": license.Customer.Id, "license_id": license.Id, @@ -786,12 +786,12 @@ func (a *App) trackLicense() { data["feature_"+featureName] = featureValue } - a.SendDiagnostic(TRACK_LICENSE, data) + s.SendDiagnostic(TRACK_LICENSE, data) } } -func (a *App) trackPlugins() { - pluginsEnvironment := a.GetPluginsEnvironment() +func (s *Server) trackPlugins() { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return } @@ -805,7 +805,7 @@ func (a *App) trackPlugins() { brokenManifestCount := 0 settingsCount := 0 - pluginStates := a.Config().PluginSettings.PluginStates + pluginStates := s.Config().PluginSettings.PluginStates plugins, _ := pluginsEnvironment.Available() if pluginStates != nil && plugins != nil { @@ -841,7 +841,7 @@ func (a *App) trackPlugins() { totalDisabledCount = -1 // -1 to indicate disabled or error } - a.SendDiagnostic(TRACK_PLUGINS, map[string]interface{}{ + s.SendDiagnostic(TRACK_PLUGINS, map[string]interface{}{ "enabled_plugins": totalEnabledCount, "enabled_webapp_plugins": webappEnabledCount, "enabled_backend_plugins": backendEnabledCount, @@ -853,82 +853,82 @@ func (a *App) trackPlugins() { }) } -func (a *App) trackServer() { +func (s *Server) trackServer() { data := map[string]interface{}{ "edition": model.BuildEnterpriseReady, "version": model.CurrentVersion, - "database_type": *a.Config().SqlSettings.DriverName, + "database_type": *s.Config().SqlSettings.DriverName, "operating_system": runtime.GOOS, } - if scr, err := a.Srv().Store.User().AnalyticsGetSystemAdminCount(); err == nil { + if scr, err := s.Store.User().AnalyticsGetSystemAdminCount(); err == nil { data["system_admins"] = scr } - if scr, err := a.Srv().Store.GetDbVersion(); err == nil { + if scr, err := s.Store.GetDbVersion(); err == nil { data["database_version"] = scr } - a.SendDiagnostic(TRACK_SERVER, data) + s.SendDiagnostic(TRACK_SERVER, data) } -func (a *App) trackPermissions() { +func (s *Server) trackPermissions() { phase1Complete := false - if _, err := a.Srv().Store.System().GetByName(ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { + if _, err := s.Store.System().GetByName(ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil { phase1Complete = true } phase2Complete := false - if _, err := a.Srv().Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err == nil { + if _, err := s.Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err == nil { phase2Complete = true } - a.SendDiagnostic(TRACK_PERMISSIONS_GENERAL, map[string]interface{}{ + s.SendDiagnostic(TRACK_PERMISSIONS_GENERAL, map[string]interface{}{ "phase_1_migration_complete": phase1Complete, "phase_2_migration_complete": phase2Complete, }) systemAdminPermissions := "" - if role, err := a.GetRoleByName(model.SYSTEM_ADMIN_ROLE_ID); err == nil { + if role, err := s.GetRoleByName(model.SYSTEM_ADMIN_ROLE_ID); err == nil { systemAdminPermissions = strings.Join(role.Permissions, " ") } systemUserPermissions := "" - if role, err := a.GetRoleByName(model.SYSTEM_USER_ROLE_ID); err == nil { + if role, err := s.GetRoleByName(model.SYSTEM_USER_ROLE_ID); err == nil { systemUserPermissions = strings.Join(role.Permissions, " ") } teamAdminPermissions := "" - if role, err := a.GetRoleByName(model.TEAM_ADMIN_ROLE_ID); err == nil { + if role, err := s.GetRoleByName(model.TEAM_ADMIN_ROLE_ID); err == nil { teamAdminPermissions = strings.Join(role.Permissions, " ") } teamUserPermissions := "" - if role, err := a.GetRoleByName(model.TEAM_USER_ROLE_ID); err == nil { + if role, err := s.GetRoleByName(model.TEAM_USER_ROLE_ID); err == nil { teamUserPermissions = strings.Join(role.Permissions, " ") } teamGuestPermissions := "" - if role, err := a.GetRoleByName(model.TEAM_GUEST_ROLE_ID); err == nil { + if role, err := s.GetRoleByName(model.TEAM_GUEST_ROLE_ID); err == nil { teamGuestPermissions = strings.Join(role.Permissions, " ") } channelAdminPermissions := "" - if role, err := a.GetRoleByName(model.CHANNEL_ADMIN_ROLE_ID); err == nil { + if role, err := s.GetRoleByName(model.CHANNEL_ADMIN_ROLE_ID); err == nil { channelAdminPermissions = strings.Join(role.Permissions, " ") } channelUserPermissions := "" - if role, err := a.GetRoleByName(model.CHANNEL_USER_ROLE_ID); err == nil { + if role, err := s.GetRoleByName(model.CHANNEL_USER_ROLE_ID); err == nil { channelUserPermissions = strings.Join(role.Permissions, " ") } channelGuestPermissions := "" - if role, err := a.GetRoleByName(model.CHANNEL_GUEST_ROLE_ID); err == nil { + if role, err := s.GetRoleByName(model.CHANNEL_GUEST_ROLE_ID); err == nil { channelGuestPermissions = strings.Join(role.Permissions, " ") } - a.SendDiagnostic(TRACK_PERMISSIONS_SYSTEM_SCHEME, map[string]interface{}{ + s.SendDiagnostic(TRACK_PERMISSIONS_SYSTEM_SCHEME, map[string]interface{}{ "system_admin_permissions": systemAdminPermissions, "system_user_permissions": systemUserPermissions, "team_admin_permissions": teamAdminPermissions, @@ -939,41 +939,41 @@ func (a *App) trackPermissions() { "channel_guest_permissions": channelGuestPermissions, }) - if schemes, err := a.GetSchemes(model.SCHEME_SCOPE_TEAM, 0, 100); err == nil { + if schemes, err := s.GetSchemes(model.SCHEME_SCOPE_TEAM, 0, 100); err == nil { for _, scheme := range schemes { teamAdminPermissions := "" - if role, err := a.GetRoleByName(scheme.DefaultTeamAdminRole); err == nil { + if role, err := s.GetRoleByName(scheme.DefaultTeamAdminRole); err == nil { teamAdminPermissions = strings.Join(role.Permissions, " ") } teamUserPermissions := "" - if role, err := a.GetRoleByName(scheme.DefaultTeamUserRole); err == nil { + if role, err := s.GetRoleByName(scheme.DefaultTeamUserRole); err == nil { teamUserPermissions = strings.Join(role.Permissions, " ") } teamGuestPermissions := "" - if role, err := a.GetRoleByName(scheme.DefaultTeamGuestRole); err == nil { + if role, err := s.GetRoleByName(scheme.DefaultTeamGuestRole); err == nil { teamGuestPermissions = strings.Join(role.Permissions, " ") } channelAdminPermissions := "" - if role, err := a.GetRoleByName(scheme.DefaultChannelAdminRole); err == nil { + if role, err := s.GetRoleByName(scheme.DefaultChannelAdminRole); err == nil { channelAdminPermissions = strings.Join(role.Permissions, " ") } channelUserPermissions := "" - if role, err := a.GetRoleByName(scheme.DefaultChannelUserRole); err == nil { + if role, err := s.GetRoleByName(scheme.DefaultChannelUserRole); err == nil { channelUserPermissions = strings.Join(role.Permissions, " ") } channelGuestPermissions := "" - if role, err := a.GetRoleByName(scheme.DefaultChannelGuestRole); err == nil { + if role, err := s.GetRoleByName(scheme.DefaultChannelGuestRole); err == nil { channelGuestPermissions = strings.Join(role.Permissions, " ") } - count, _ := a.Srv().Store.Team().AnalyticsGetTeamCountForScheme(scheme.Id) + count, _ := s.Store.Team().AnalyticsGetTeamCountForScheme(scheme.Id) - a.SendDiagnostic(TRACK_PERMISSIONS_TEAM_SCHEMES, map[string]interface{}{ + s.SendDiagnostic(TRACK_PERMISSIONS_TEAM_SCHEMES, map[string]interface{}{ "scheme_id": scheme.Id, "team_admin_permissions": teamAdminPermissions, "team_user_permissions": teamUserPermissions, @@ -987,60 +987,60 @@ func (a *App) trackPermissions() { } } -func (a *App) trackElasticsearch() { +func (s *Server) trackElasticsearch() { data := map[string]interface{}{} - for _, engine := range a.SearchEngine().GetActiveEngines() { + for _, engine := range s.SearchEngine.GetActiveEngines() { if engine.GetVersion() != 0 && engine.GetName() == "elasticsearch" { data["elasticsearch_server_version"] = engine.GetVersion() } } - a.SendDiagnostic(TRACK_ELASTICSEARCH, data) + s.SendDiagnostic(TRACK_ELASTICSEARCH, data) } -func (a *App) trackGroups() { - groupCount, err := a.Srv().Store.Group().GroupCount() +func (s *Server) trackGroups() { + groupCount, err := s.Store.Group().GroupCount() if err != nil { mlog.Error(err.Error()) } - groupTeamCount, err := a.Srv().Store.Group().GroupTeamCount() + groupTeamCount, err := s.Store.Group().GroupTeamCount() if err != nil { mlog.Error(err.Error()) } - groupChannelCount, err := a.Srv().Store.Group().GroupChannelCount() + groupChannelCount, err := s.Store.Group().GroupChannelCount() if err != nil { mlog.Error(err.Error()) } - groupSyncedTeamCount, err := a.Srv().Store.Team().GroupSyncedTeamCount() + groupSyncedTeamCount, err := s.Store.Team().GroupSyncedTeamCount() if err != nil { mlog.Error(err.Error()) } - groupSyncedChannelCount, err := a.Srv().Store.Channel().GroupSyncedChannelCount() + groupSyncedChannelCount, err := s.Store.Channel().GroupSyncedChannelCount() if err != nil { mlog.Error(err.Error()) } - groupMemberCount, err := a.Srv().Store.Group().GroupMemberCount() + groupMemberCount, err := s.Store.Group().GroupMemberCount() if err != nil { mlog.Error(err.Error()) } - distinctGroupMemberCount, err := a.Srv().Store.Group().DistinctGroupMemberCount() + distinctGroupMemberCount, err := s.Store.Group().DistinctGroupMemberCount() if err != nil { mlog.Error(err.Error()) } - groupCountWithAllowReference, err := a.Srv().Store.Group().GroupCountWithAllowReference() + groupCountWithAllowReference, err := s.Store.Group().GroupCountWithAllowReference() if err != nil { mlog.Error(err.Error()) } - a.SendDiagnostic(TRACK_GROUPS, map[string]interface{}{ + s.SendDiagnostic(TRACK_GROUPS, map[string]interface{}{ "group_count": groupCount, "group_team_count": groupTeamCount, "group_channel_count": groupChannelCount, @@ -1052,50 +1052,50 @@ func (a *App) trackGroups() { }) } -func (a *App) trackChannelModeration() { - channelSchemeCount, err := a.Srv().Store.Scheme().CountByScope(model.SCHEME_SCOPE_CHANNEL) +func (s *Server) trackChannelModeration() { + channelSchemeCount, err := s.Store.Scheme().CountByScope(model.SCHEME_SCOPE_CHANNEL) if err != nil { mlog.Error(err.Error()) } - createPostUser, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeUser) + createPostUser, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeUser) if err != nil { mlog.Error(err.Error()) } - createPostGuest, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeGuest) + createPostGuest, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_CREATE_POST.Id, model.RoleScopeChannel, model.RoleTypeGuest) if err != nil { mlog.Error(err.Error()) } // only need to track one of 'add_reaction' or 'remove_reaction` because they're both toggled together by the channel moderation feature - postReactionsUser, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeUser) + postReactionsUser, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeUser) if err != nil { mlog.Error(err.Error()) } - postReactionsGuest, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeGuest) + postReactionsGuest, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_ADD_REACTION.Id, model.RoleScopeChannel, model.RoleTypeGuest) if err != nil { mlog.Error(err.Error()) } // only need to track one of 'manage_public_channel_members' or 'manage_private_channel_members` because they're both toggled together by the channel moderation feature - manageMembersUser, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, model.RoleScopeChannel, model.RoleTypeUser) + manageMembersUser, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS.Id, model.RoleScopeChannel, model.RoleTypeUser) if err != nil { mlog.Error(err.Error()) } - useChannelMentionsUser, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeUser) + useChannelMentionsUser, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeUser) if err != nil { mlog.Error(err.Error()) } - useChannelMentionsGuest, err := a.Srv().Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeGuest) + useChannelMentionsGuest, err := s.Store.Scheme().CountWithoutPermission(model.SCHEME_SCOPE_CHANNEL, model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.RoleScopeChannel, model.RoleTypeGuest) if err != nil { mlog.Error(err.Error()) } - a.SendDiagnostic(TRACK_CHANNEL_MODERATION, map[string]interface{}{ + s.SendDiagnostic(TRACK_CHANNEL_MODERATION, map[string]interface{}{ "channel_scheme_count": channelSchemeCount, "create_post_user_disabled_count": createPostUser, diff --git a/app/diagnostics_test.go b/app/diagnostics_test.go index 51396c0e90..5b9681a7ad 100644 --- a/app/diagnostics_test.go +++ b/app/diagnostics_test.go @@ -136,7 +136,7 @@ func TestSegmentDiagnostics(t *testing.T) { t.Run("Send", func(t *testing.T) { testValue := "test-send-value-6789" - th.App.SendDiagnostic("Testing Diagnostic", map[string]interface{}{ + th.App.Srv().SendDiagnostic("Testing Diagnostic", map[string]interface{}{ "hey": testValue, }) select { @@ -151,7 +151,7 @@ func TestSegmentDiagnostics(t *testing.T) { // Plugins remain disabled at this point t.Run("SendDailyDiagnosticsPluginsDisabled", func(t *testing.T) { - th.App.sendDailyDiagnostics(true) + th.App.Srv().sendDailyDiagnostics(true) var info []string // Collect the info sent. @@ -203,7 +203,7 @@ func TestSegmentDiagnostics(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true }) t.Run("SendDailyDiagnostics", func(t *testing.T) { - th.App.sendDailyDiagnostics(true) + th.App.Srv().sendDailyDiagnostics(true) var info []string // Collect the info sent. @@ -252,7 +252,7 @@ func TestSegmentDiagnostics(t *testing.T) { }) t.Run("SendDailyDiagnosticsNoSegmentKey", func(t *testing.T) { - th.App.SendDailyDiagnostics() + th.App.Srv().SendDailyDiagnostics() select { case <-data: @@ -265,7 +265,7 @@ func TestSegmentDiagnostics(t *testing.T) { t.Run("SendDailyDiagnosticsDisabled", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LogSettings.EnableDiagnostics = false }) - th.App.sendDailyDiagnostics(true) + th.App.Srv().sendDailyDiagnostics(true) select { case <-data: @@ -363,7 +363,7 @@ func TestRudderDiagnostics(t *testing.T) { t.Run("Send", func(t *testing.T) { testValue := "test-send-value-6789" - th.App.SendDiagnostic("Testing Diagnostic", map[string]interface{}{ + th.App.Srv().SendDiagnostic("Testing Diagnostic", map[string]interface{}{ "hey": testValue, }) select { @@ -378,7 +378,7 @@ func TestRudderDiagnostics(t *testing.T) { // Plugins remain disabled at this point t.Run("SendDailyDiagnosticsPluginsDisabled", func(t *testing.T) { - th.App.sendDailyDiagnostics(true) + th.App.Srv().sendDailyDiagnostics(true) var info []string // Collect the info sent. @@ -420,7 +420,7 @@ func TestRudderDiagnostics(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PluginSettings.Enable = true }) t.Run("SendDailyDiagnostics", func(t *testing.T) { - th.App.sendDailyDiagnostics(true) + th.App.Srv().sendDailyDiagnostics(true) var info []string // Collect the info sent. @@ -459,7 +459,7 @@ func TestRudderDiagnostics(t *testing.T) { }) t.Run("SendDailyDiagnosticsNoRudderKey", func(t *testing.T) { - th.App.SendDailyDiagnostics() + th.App.Srv().SendDailyDiagnostics() select { case <-data: @@ -472,7 +472,7 @@ func TestRudderDiagnostics(t *testing.T) { t.Run("SendDailyDiagnosticsDisabled", func(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.LogSettings.EnableDiagnostics = false }) - th.App.sendDailyDiagnostics(true) + th.App.Srv().sendDailyDiagnostics(true) select { case <-data: diff --git a/app/email.go b/app/email.go index ae00690283..e2cc771f86 100644 --- a/app/email.go +++ b/app/email.go @@ -39,7 +39,7 @@ func condenseSiteURL(siteURL string) string { return path.Join(parsedSiteURL.Host, parsedSiteURL.Path) } -func (a *App) SetupInviteEmailRateLimiting() error { +func (s *Server) setupInviteEmailRateLimiting() error { store, err := memstore.New(emailRateLimitingMemstoreSize) if err != nil { return errors.Wrap(err, "Unable to setup email rate limiting memstore.") @@ -55,7 +55,7 @@ func (a *App) SetupInviteEmailRateLimiting() error { return errors.Wrap(err, "Unable to setup email rate limiting GCRA rate limiter.") } - a.Srv().EmailRateLimiter = rateLimiter + s.EmailRateLimiter = rateLimiter return nil } @@ -463,8 +463,8 @@ func (a *App) sendGuestInviteEmails(team *model.Team, channels []*model.Channel, } } -func (a *App) newEmailTemplate(name, locale string) *utils.HTMLTemplate { - t := utils.NewHTMLTemplate(a.HTMLTemplates(), name) +func (s *Server) newEmailTemplate(name, locale string) *utils.HTMLTemplate { + t := utils.NewHTMLTemplate(s.HTMLTemplates(), name) var localT i18n.TranslateFunc if locale != "" { @@ -475,8 +475,8 @@ func (a *App) newEmailTemplate(name, locale string) *utils.HTMLTemplate { t.Props["Footer"] = localT("api.templates.email_footer") - if *a.Config().EmailSettings.FeedbackOrganization != "" { - t.Props["Organization"] = localT("api.templates.email_organization") + *a.Config().EmailSettings.FeedbackOrganization + if *s.Config().EmailSettings.FeedbackOrganization != "" { + t.Props["Organization"] = localT("api.templates.email_organization") + *s.Config().EmailSettings.FeedbackOrganization } else { t.Props["Organization"] = "" } @@ -484,12 +484,16 @@ func (a *App) newEmailTemplate(name, locale string) *utils.HTMLTemplate { t.Props["EmailInfo1"] = localT("api.templates.email_info1") t.Props["EmailInfo2"] = localT("api.templates.email_info2") t.Props["EmailInfo3"] = localT("api.templates.email_info3", - map[string]interface{}{"SiteName": a.Config().TeamSettings.SiteName}) - t.Props["SupportEmail"] = *a.Config().SupportSettings.SupportEmail + map[string]interface{}{"SiteName": s.Config().TeamSettings.SiteName}) + t.Props["SupportEmail"] = *s.Config().SupportSettings.SupportEmail return t } +func (a *App) newEmailTemplate(name, locale string) *utils.HTMLTemplate { + return a.Srv().newEmailTemplate(name, locale) +} + func (a *App) SendDeactivateAccountEmail(email string, locale, siteURL string) *model.AppError { T := utils.GetUserTranslations(locale) @@ -531,21 +535,33 @@ func (a *App) SendRemoveExpiredLicenseEmail(email string, locale, siteURL string return nil } -func (a *App) sendNotificationMail(to, subject, htmlBody string) *model.AppError { - if !*a.Config().EmailSettings.SendEmailNotifications { +func (s *Server) sendNotificationMail(to, subject, htmlBody string) *model.AppError { + if !*s.Config().EmailSettings.SendEmailNotifications { return nil } - return a.sendMail(to, subject, htmlBody) + return s.sendMail(to, subject, htmlBody) +} + +func (a *App) sendNotificationMail(to, subject, htmlBody string) *model.AppError { + return a.Srv().sendNotificationMail(to, subject, htmlBody) +} + +func (s *Server) sendMail(to, subject, htmlBody string) *model.AppError { + license := s.License() + return mailservice.SendMailUsingConfig(to, subject, htmlBody, s.Config(), license != nil && *license.Features.Compliance) } func (a *App) sendMail(to, subject, htmlBody string) *model.AppError { - license := a.License() - return mailservice.SendMailUsingConfig(to, subject, htmlBody, a.Config(), license != nil && *license.Features.Compliance) + return a.Srv().sendMail(to, subject, htmlBody) } -func (a *App) sendMailWithEmbeddedFiles(to, subject, htmlBody string, embeddedFiles map[string]io.Reader) *model.AppError { - license := a.License() - config := a.Config() +func (s *Server) sendMailWithEmbeddedFiles(to, subject, htmlBody string, embeddedFiles map[string]io.Reader) *model.AppError { + license := s.License() + config := s.Config() return mailservice.SendMailWithEmbeddedFilesUsingConfig(to, subject, htmlBody, embeddedFiles, config, license != nil && *license.Features.Compliance) } + +func (a *App) sendMailWithEmbeddedFiles(to, subject, htmlBody string, embeddedFiles map[string]io.Reader) *model.AppError { + return a.Srv().sendMailWithEmbeddedFiles(to, subject, htmlBody, embeddedFiles) +} diff --git a/app/email_batching.go b/app/email_batching.go index 56c3889ec5..df430e79f4 100644 --- a/app/email_batching.go +++ b/app/email_batching.go @@ -235,12 +235,12 @@ func (s *Server) sendBatchedEmailNotification(userId string, notifications []*ba "Day": tm.Day(), }) - body := s.FakeApp().newEmailTemplate("post_batched_body", user.Locale) + body := s.newEmailTemplate("post_batched_body", user.Locale) body.Props["SiteURL"] = *s.Config().ServiceSettings.SiteURL body.Props["Posts"] = template.HTML(contents) body.Props["BodyText"] = translateFunc("api.email_batching.send_batched_email_notification.body_text", len(notifications)) - if err := s.FakeApp().sendNotificationMail(user.Email, subject, body.Render()); err != nil { + if err := s.sendNotificationMail(user.Email, subject, body.Render()); err != nil { mlog.Warn("Unable to send batched email notification", mlog.String("email", user.Email), mlog.Err(err)) } } @@ -249,13 +249,13 @@ func (s *Server) renderBatchedPost(notification *batchedNotification, channel *m // don't include message contents if email notification contents type is set to generic var template *utils.HTMLTemplate if emailNotificationContentsType == model.EMAIL_NOTIFICATION_CONTENTS_FULL { - template = s.FakeApp().newEmailTemplate("post_batched_post_full", userLocale) + template = s.newEmailTemplate("post_batched_post_full", userLocale) } else { - template = s.FakeApp().newEmailTemplate("post_batched_post_generic", userLocale) + template = s.newEmailTemplate("post_batched_post_generic", userLocale) } template.Props["Button"] = translateFunc("api.email_batching.render_batched_post.go_to_post") - template.Props["PostMessage"] = s.FakeApp().GetMessageForNotification(notification.post, translateFunc) + template.Props["PostMessage"] = s.GetMessageForNotification(notification.post, translateFunc) template.Props["PostLink"] = siteURL + "/" + notification.teamName + "/pl/" + notification.post.Id template.Props["SenderName"] = sender.GetDisplayName(displayNameFormat) diff --git a/app/enterprise.go b/app/enterprise.go index 2a46798cc9..131d0dc21d 100644 --- a/app/enterprise.go +++ b/app/enterprise.go @@ -12,9 +12,9 @@ import ( "github.com/mattermost/mattermost-server/v5/services/searchengine" ) -var accountMigrationInterface func(*Server) einterfaces.AccountMigrationInterface +var accountMigrationInterface func(*App) einterfaces.AccountMigrationInterface -func RegisterAccountMigrationInterface(f func(*Server) einterfaces.AccountMigrationInterface) { +func RegisterAccountMigrationInterface(f func(*App) einterfaces.AccountMigrationInterface) { accountMigrationInterface = f } @@ -130,43 +130,45 @@ func (s *Server) initEnterprise() { if metricsInterface != nil { s.Metrics = metricsInterface(s) } - if accountMigrationInterface != nil { - s.AccountMigration = accountMigrationInterface(s) - } if complianceInterface != nil { s.Compliance = complianceInterface(s) } - if ldapInterface != nil { - s.Ldap = ldapInterface(s.FakeApp()) - } if messageExportInterface != nil { s.MessageExport = messageExportInterface(s) } - if notificationInterface != nil { - s.Notification = notificationInterface(s.FakeApp()) - } - if samlInterface != nil { - if *s.FakeApp().Config().ExperimentalSettings.UseNewSAMLLibrary && samlInterfaceNew != nil { - mlog.Debug("Loading new SAML2 library") - s.Saml = samlInterfaceNew(s.FakeApp()) - } else { - mlog.Debug("Loading original SAML library") - s.Saml = samlInterface(s.FakeApp()) - } - s.AddConfigListener(func(_, cfg *model.Config) { - if err := s.Saml.ConfigureSP(); err != nil { - mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) - } - }) - } if dataRetentionInterface != nil { s.DataRetention = dataRetentionInterface(s) } if clusterInterface != nil { s.Cluster = clusterInterface(s) } - if elasticsearchInterface != nil { s.SearchEngine.RegisterElasticsearchEngine(elasticsearchInterface(s)) } } + +func (a *App) initEnterprise() { + if accountMigrationInterface != nil { + a.srv.AccountMigration = accountMigrationInterface(a) + } + if ldapInterface != nil { + a.srv.Ldap = ldapInterface(a) + } + if notificationInterface != nil { + a.srv.Notification = notificationInterface(a) + } + if samlInterface != nil { + if *a.Config().ExperimentalSettings.UseNewSAMLLibrary && samlInterfaceNew != nil { + mlog.Debug("Loading new SAML2 library") + a.srv.Saml = samlInterfaceNew(a) + } else { + mlog.Debug("Loading original SAML library") + a.srv.Saml = samlInterface(a) + } + a.AddConfigListener(func(_, cfg *model.Config) { + if err := a.srv.Saml.ConfigureSP(); err != nil { + mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err)) + } + }) + } +} diff --git a/app/enterprise_test.go b/app/enterprise_test.go index 4cd3e041c9..c9ffc65cd7 100644 --- a/app/enterprise_test.go +++ b/app/enterprise_test.go @@ -118,6 +118,7 @@ func TestSAMLSettings(t *testing.T) { } th.Server.initEnterprise() + th.App.initEnterprise() if tc.isNil { assert.Nil(t, th.App.Srv().Saml) } else { diff --git a/app/helper_test.go b/app/helper_test.go index 1c36c728c4..273631e677 100644 --- a/app/helper_test.go +++ b/app/helper_test.go @@ -80,7 +80,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo } th := &TestHelper{ - App: s.FakeApp(), + App: New(ServerConnector(s)), Server: s, LogBuffer: buffer, IncludeCacheLayer: includeCacheLayer, @@ -113,15 +113,17 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo }) if enterprise { - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) } else { - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) } if th.tempWorkspace == "" { th.tempWorkspace = tempWorkspace } + th.App.InitServer() + return th } @@ -584,7 +586,7 @@ func (me *TestHelper) ShutdownApp() { func (me *TestHelper) TearDown() { if me.IncludeCacheLayer { // Clean all the caches - me.App.InvalidateAllCaches() + me.App.Srv().InvalidateAllCaches() } me.ShutdownApp() if me.tempWorkspace != "" { diff --git a/app/ldap.go b/app/ldap.go index bd92a6ff86..83e9be7ebc 100644 --- a/app/ldap.go +++ b/app/ldap.go @@ -14,7 +14,7 @@ import ( func (a *App) SyncLdap() { a.Srv().Go(func() { - if license := a.License(); license != nil && *license.Features.LDAP && *a.Config().LdapSettings.EnableSync { + if license := a.Srv().License(); license != nil && *license.Features.LDAP && *a.Config().LdapSettings.EnableSync { if ldapI := a.Ldap(); ldapI != nil { ldapI.StartSynchronizeJob(false) } else { @@ -25,7 +25,7 @@ func (a *App) SyncLdap() { } func (a *App) TestLdap() *model.AppError { - license := a.License() + license := a.Srv().License() if ldapI := a.Ldap(); ldapI != nil && license != nil && *license.Features.LDAP && (*a.Config().LdapSettings.Enable || *a.Config().LdapSettings.EnableSync) { if err := ldapI.RunTest(); err != nil { err.StatusCode = 500 @@ -80,7 +80,7 @@ func (a *App) GetAllLdapGroupsPage(page int, perPage int, opts model.LdapGroupSe } func (a *App) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError) { - if a.License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { + if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { return "", model.NewAppError("emailToLdap", "api.user.email_to_ldap.not_available.app_error", nil, "", http.StatusForbidden) } @@ -116,7 +116,7 @@ func (a *App) SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword } func (a *App) SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (string, *model.AppError) { - if a.License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { + if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { return "", model.NewAppError("ldapToEmail", "api.user.ldap_to_email.not_available.app_error", nil, "", http.StatusForbidden) } diff --git a/app/license.go b/app/license.go index a8441ceda2..314af4213a 100644 --- a/app/license.go +++ b/app/license.go @@ -15,19 +15,19 @@ import ( const requestTrialURL = "https://customers.mattermost.com/api/v1/trials" -func (a *App) LoadLicense() { +func (s *Server) LoadLicense() { licenseId := "" - props, err := a.Srv().Store.System().Get() + props, err := s.Store.System().Get() if err == nil { licenseId = props[model.SYSTEM_ACTIVE_LICENSE_ID] } if !model.IsValidId(licenseId) { // Lets attempt to load the file from disk since it was missing from the DB - license, licenseBytes := utils.GetAndValidateLicenseFileFromDisk(*a.Config().ServiceSettings.LicenseFileLocation) + license, licenseBytes := utils.GetAndValidateLicenseFileFromDisk(*s.Config().ServiceSettings.LicenseFileLocation) if license != nil { - if _, err = a.SaveLicense(licenseBytes); err != nil { + if _, err = s.SaveLicense(licenseBytes); err != nil { mlog.Info("Failed to save license key loaded from disk.", mlog.Err(err)) } else { licenseId = license.Id @@ -35,25 +35,25 @@ func (a *App) LoadLicense() { } } - record, err := a.Srv().Store.License().Get(licenseId) + record, err := s.Store.License().Get(licenseId) if err != nil { mlog.Info("License key from https://mattermost.com required to unlock enterprise features.") - a.SetLicense(nil) + s.SetLicense(nil) return } - a.ValidateAndSetLicenseBytes([]byte(record.Bytes)) + s.ValidateAndSetLicenseBytes([]byte(record.Bytes)) mlog.Info("License key valid unlocking enterprise features.") } -func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { +func (s *Server) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { success, licenseStr := utils.ValidateLicense(licenseBytes) if !success { return nil, model.NewAppError("addLicense", model.INVALID_LICENSE_ERROR, nil, "", http.StatusBadRequest) } license := model.LicenseFromJson(strings.NewReader(licenseStr)) - uniqueUserCount, err := a.Srv().Store.User().Count(model.UserCountOptions{}) + uniqueUserCount, err := s.Store.User().Count(model.UserCountOptions{}) if err != nil { return nil, model.NewAppError("addLicense", "api.license.add_license.invalid_count.app_error", nil, err.Error(), http.StatusBadRequest) } @@ -66,7 +66,7 @@ func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest) } - if ok := a.SetLicense(license); !ok { + if ok := s.SetLicense(license); !ok { return nil, model.NewAppError("addLicense", model.EXPIRED_LICENSE_ERROR, nil, "", http.StatusBadRequest) } @@ -74,46 +74,41 @@ func (a *App) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) record.Id = license.Id record.Bytes = string(licenseBytes) - _, err = a.Srv().Store.License().Save(record) + _, err = s.Store.License().Save(record) if err != nil { - a.RemoveLicense() + s.RemoveLicense() return nil, model.NewAppError("addLicense", "api.license.add_license.save.app_error", nil, "err="+err.Error(), http.StatusInternalServerError) } sysVar := &model.System{} sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID sysVar.Value = license.Id - if err := a.Srv().Store.System().SaveOrUpdate(sysVar); err != nil { - a.RemoveLicense() + if err := s.Store.System().SaveOrUpdate(sysVar); err != nil { + s.RemoveLicense() return nil, model.NewAppError("addLicense", "api.license.add_license.save_active.app_error", nil, "", http.StatusInternalServerError) } - a.ReloadConfig() - a.InvalidateAllCaches() + s.ReloadConfig() + s.InvalidateAllCaches() // start job server if necessary - this handles the edge case where a license file is uploaded, but the job server // doesn't start until the server is restarted, which prevents the 'run job now' buttons in system console from // functioning as expected - if *a.Config().JobSettings.RunJobs && a.Srv().Jobs != nil && a.Srv().Jobs.Workers != nil { - a.Srv().Jobs.StartWorkers() + if *s.Config().JobSettings.RunJobs && s.Jobs != nil && s.Jobs.Workers != nil { + s.Jobs.StartWorkers() } - if *a.Config().JobSettings.RunScheduler && a.Srv().Jobs != nil && a.Srv().Jobs.Schedulers != nil { - a.Srv().Jobs.StartSchedulers() + if *s.Config().JobSettings.RunScheduler && s.Jobs != nil && s.Jobs.Schedulers != nil { + s.Jobs.StartSchedulers() } return license, nil } -// License returns the currently active license or nil if the application is unlicensed. -func (a *App) License() *model.License { - return a.Srv().License() -} - -func (a *App) SetLicense(license *model.License) bool { - oldLicense := a.Srv().licenseValue.Load() +func (s *Server) SetLicense(license *model.License) bool { + oldLicense := s.licenseValue.Load() defer func() { - for _, listener := range a.Srv().licenseListeners { + for _, listener := range s.licenseListeners { if oldLicense == nil { listener(nil, license) } else { @@ -125,39 +120,39 @@ func (a *App) SetLicense(license *model.License) bool { if license != nil { license.Features.SetDefaults() - a.Srv().licenseValue.Store(license) - a.Srv().clientLicenseValue.Store(utils.GetClientLicense(license)) + s.licenseValue.Store(license) + s.clientLicenseValue.Store(utils.GetClientLicense(license)) return true } - a.Srv().licenseValue.Store((*model.License)(nil)) - a.Srv().clientLicenseValue.Store(map[string]string(nil)) + s.licenseValue.Store((*model.License)(nil)) + s.clientLicenseValue.Store(map[string]string(nil)) return false } -func (a *App) ValidateAndSetLicenseBytes(b []byte) { +func (s *Server) ValidateAndSetLicenseBytes(b []byte) { if success, licenseStr := utils.ValidateLicense(b); success { license := model.LicenseFromJson(strings.NewReader(licenseStr)) - a.SetLicense(license) + s.SetLicense(license) return } mlog.Warn("No valid enterprise license found") } -func (a *App) SetClientLicense(m map[string]string) { - a.Srv().clientLicenseValue.Store(m) +func (s *Server) SetClientLicense(m map[string]string) { + s.clientLicenseValue.Store(m) } -func (a *App) ClientLicense() map[string]string { - if clientLicense, _ := a.Srv().clientLicenseValue.Load().(map[string]string); clientLicense != nil { +func (s *Server) ClientLicense() map[string]string { + if clientLicense, _ := s.clientLicenseValue.Load().(map[string]string); clientLicense != nil { return clientLicense } return map[string]string{"IsLicensed": "false"} } -func (a *App) RemoveLicense() *model.AppError { - if license, _ := a.Srv().licenseValue.Load().(*model.License); license == nil { +func (s *Server) RemoveLicense() *model.AppError { + if license, _ := s.licenseValue.Load().(*model.License); license == nil { return nil } @@ -167,14 +162,13 @@ func (a *App) RemoveLicense() *model.AppError { sysVar.Name = model.SYSTEM_ACTIVE_LICENSE_ID sysVar.Value = "" - if err := a.Srv().Store.System().SaveOrUpdate(sysVar); err != nil { + if err := s.Store.System().SaveOrUpdate(sysVar); err != nil { return err } - a.SetLicense(nil) - a.ReloadConfig() - - a.InvalidateAllCaches() + s.SetLicense(nil) + s.ReloadConfig() + s.InvalidateAllCaches() return nil } @@ -185,24 +179,14 @@ func (s *Server) AddLicenseListener(listener func(oldLicense, newLicense *model. return id } -func (a *App) AddLicenseListener(listener func(oldLicense, newLicense *model.License)) string { - id := model.NewId() - a.Srv().licenseListeners[id] = listener - return id -} - func (s *Server) RemoveLicenseListener(id string) { delete(s.licenseListeners, id) } -func (a *App) RemoveLicenseListener(id string) { - delete(a.Srv().licenseListeners, id) -} - -func (a *App) GetSanitizedClientLicense() map[string]string { +func (s *Server) GetSanitizedClientLicense() map[string]string { sanitizedLicense := make(map[string]string) - for k, v := range a.ClientLicense() { + for k, v := range s.ClientLicense() { sanitizedLicense[k] = v } @@ -219,7 +203,7 @@ func (a *App) GetSanitizedClientLicense() map[string]string { } // RequestTrialLicense request a trial license from the mattermost offical license server -func (a *App) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError { +func (s *Server) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError { resp, err := http.Post(requestTrialURL, "application/json", bytes.NewBuffer([]byte(trialRequest.ToJson()))) if err != nil { return model.NewAppError("RequestTrialLicense", "api.license.request_trial_license.app_error", nil, err.Error(), http.StatusBadRequest) @@ -227,12 +211,12 @@ func (a *App) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *mode defer resp.Body.Close() licenseResponse := model.MapFromJson(resp.Body) - if _, err := a.SaveLicense([]byte(licenseResponse["license"])); err != nil { + if _, err := s.SaveLicense([]byte(licenseResponse["license"])); err != nil { return err } - a.ReloadConfig() - a.InvalidateAllCaches() + s.ReloadConfig() + s.InvalidateAllCaches() return nil } diff --git a/app/license_test.go b/app/license_test.go index 3bd5ea2e05..40116ee414 100644 --- a/app/license_test.go +++ b/app/license_test.go @@ -15,8 +15,8 @@ func TestLoadLicense(t *testing.T) { th := Setup(t) defer th.TearDown() - th.App.LoadLicense() - require.Nil(t, th.App.License(), "shouldn't have a valid license") + th.App.Srv().LoadLicense() + require.Nil(t, th.App.Srv().License(), "shouldn't have a valid license") } func TestSaveLicense(t *testing.T) { @@ -25,7 +25,7 @@ func TestSaveLicense(t *testing.T) { b1 := []byte("junk") - _, err := th.App.SaveLicense(b1) + _, err := th.App.Srv().SaveLicense(b1) require.NotNil(t, err, "shouldn't have saved license") } @@ -33,7 +33,7 @@ func TestRemoveLicense(t *testing.T) { th := Setup(t) defer th.TearDown() - err := th.App.RemoveLicense() + err := th.App.Srv().RemoveLicense() require.Nil(t, err, "should have removed license") } @@ -46,7 +46,7 @@ func TestSetLicense(t *testing.T) { l1.Customer = &model.Customer{} l1.StartsAt = model.GetMillis() - 1000 l1.ExpiresAt = model.GetMillis() + 100000 - ok := th.App.SetLicense(l1) + ok := th.App.Srv().SetLicense(l1) require.True(t, ok, "license should have worked") l3 := &model.License{} @@ -54,7 +54,7 @@ func TestSetLicense(t *testing.T) { l3.Customer = &model.Customer{} l3.StartsAt = model.GetMillis() + 10000 l3.ExpiresAt = model.GetMillis() + 100000 - ok = th.App.SetLicense(l3) + ok = th.App.Srv().SetLicense(l3) require.True(t, ok, "license should have passed") } @@ -70,9 +70,9 @@ func TestGetSanitizedClientLicense(t *testing.T) { l1.SkuShortName = "SKU SHORT NAME" l1.StartsAt = model.GetMillis() - 1000 l1.ExpiresAt = model.GetMillis() + 100000 - th.App.SetLicense(l1) + th.App.Srv().SetLicense(l1) - m := th.App.GetSanitizedClientLicense() + m := th.App.Srv().GetSanitizedClientLicense() _, ok := m["Name"] assert.False(t, ok) diff --git a/app/migrations.go b/app/migrations.go index 61da16e07c..404de7dffc 100644 --- a/app/migrations.go +++ b/app/migrations.go @@ -25,7 +25,7 @@ func (a *App) DoAdvancedPermissionsMigration() { mlog.Info("Migrating roles to database.") roles := model.MakeDefaultRoles() - roles = utils.SetRolePermissionsFromConfig(roles, a.Config(), a.License() != nil) + roles = utils.SetRolePermissionsFromConfig(roles, a.Config(), a.Srv().License() != nil) allSucceeded := true diff --git a/app/notification.go b/app/notification.go index cef8ada347..7e3a532591 100644 --- a/app/notification.go +++ b/app/notification.go @@ -250,7 +250,7 @@ func (a *App) SendNotifications(post *model.Post, team *model.Team, channel *mod sendPushNotifications := false if *a.Config().EmailSettings.SendPushNotifications { pushServer := *a.Config().EmailSettings.PushNotificationServer - if license := a.License(); pushServer == model.MHPNS && (license == nil || !*license.Features.MHPNS) { + if license := a.Srv().License(); pushServer == model.MHPNS && (license == nil || !*license.Features.MHPNS) { mlog.Warn("Push notifications are disabled. Go to System Console > Notifications > Mobile Push to enable them.") sendPushNotifications = false } else { @@ -737,7 +737,7 @@ func (a *App) allowChannelMentions(post *model.Post, numProfiles int) bool { // allowGroupMentions returns whether or not the group mentions are allowed for the given post. func (a *App) allowGroupMentions(post *model.Post) bool { - if license := a.License(); license == nil || !*license.Features.LDAPGroups { + if license := a.Srv().License(); license == nil || !*license.Features.LDAPGroups { return false } diff --git a/app/notification_email.go b/app/notification_email.go index 4796f962fa..326039f29a 100644 --- a/app/notification_email.go +++ b/app/notification_email.go @@ -80,7 +80,7 @@ func (a *App) sendNotificationEmail(notification *PostNotification, user *model. senderName := notification.GetSenderName(nameFormat, *a.Config().ServiceSettings.EnablePostUsernameOverride) emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL - if license := a.License(); license != nil && *license.Features.EmailNotificationContents { + if license := a.Srv().License(); license != nil && *license.Features.EmailNotificationContents { emailNotificationContentsType = *a.Config().EmailSettings.EmailNotificationContentsType } @@ -312,13 +312,13 @@ func (a *App) generateHyperlinkForChannels(postMessage, teamName, teamURL string return postMessage } -func (a *App) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string { +func (s *Server) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string { if len(strings.TrimSpace(post.Message)) != 0 || len(post.FileIds) == 0 { return post.Message } // extract the filenames from their paths and determine what type of files are attached - infos, err := a.Srv().Store.FileInfo().GetForPost(post.Id, true, false, true) + infos, err := s.Store.FileInfo().GetForPost(post.Id, true, false, true) if err != nil { mlog.Warn("Encountered error when getting files for notification message", mlog.String("post_id", post.Id), mlog.Err(err)) } @@ -343,3 +343,7 @@ func (a *App) GetMessageForNotification(post *model.Post, translateFunc i18n.Tra } return translateFunc("api.post.get_message_for_notification.files_sent", len(filenames), props) } + +func (a *App) GetMessageForNotification(post *model.Post, translateFunc i18n.TranslateFunc) string { + return a.Srv().GetMessageForNotification(post, translateFunc) +} diff --git a/app/notification_push.go b/app/notification_push.go index 4841b72145..fc4c2b607e 100644 --- a/app/notification_push.go +++ b/app/notification_push.go @@ -252,14 +252,14 @@ func (a *App) UpdateMobileAppBadge(userId string) { } } -func (a *App) createPushNotificationsHub() { +func (s *Server) createPushNotificationsHub() { hub := PushNotificationsHub{ Channels: []chan PushNotification{}, } for x := 0; x < PUSH_NOTIFICATION_HUB_WORKERS; x++ { hub.Channels = append(hub.Channels, make(chan PushNotification, PUSH_NOTIFICATIONS_HUB_BUFFER_PER_WORKER)) } - a.Srv().PushNotificationsHub = hub + s.PushNotificationsHub = hub } func (a *App) pushNotificationWorker(notifications chan PushNotification) { @@ -298,8 +298,8 @@ func (a *App) StartPushNotificationsHubWorkers() { } } -func (a *App) StopPushNotificationsHubWorkers() { - for _, channel := range a.Srv().PushNotificationsHub.Channels { +func (s *Server) StopPushNotificationsHubWorkers() { + for _, channel := range s.PushNotificationsHub.Channels { close(channel) } } diff --git a/app/notification_test.go b/app/notification_test.go index 22f4251ab4..9dd4b71ce6 100644 --- a/app/notification_test.go +++ b/app/notification_test.go @@ -50,7 +50,7 @@ func TestSendNotifications(t *testing.T) { _, appErr = th.App.UpdateActive(th.BasicUser2, false) require.Nil(t, appErr) - appErr = th.App.InvalidateAllCaches() + appErr = th.App.Srv().InvalidateAllCaches() require.Nil(t, appErr) post3, appErr := th.App.CreatePostMissingChannel(&model.Post{ @@ -1004,7 +1004,7 @@ func TestAllowGroupMentions(t *testing.T) { assert.False(t, allowGroupMentions) }) - th.App.SetLicense(model.NewTestLicense("ldap_groups")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap_groups")) t.Run("should return true for a regular post with few channel members", func(t *testing.T) { allowGroupMentions := th.App.allowGroupMentions(post) diff --git a/app/oauth.go b/app/oauth.go index dab15ae198..e00be718e0 100644 --- a/app/oauth.go +++ b/app/oauth.go @@ -66,7 +66,7 @@ func (a *App) DeleteOAuthApp(appId string) *model.AppError { return err } - if err := a.InvalidateAllCaches(); err != nil { + if err := a.Srv().InvalidateAllCaches(); err != nil { mlog.Error("error in invalidating cache", mlog.Err(err)) } @@ -801,7 +801,7 @@ func (a *App) AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service } func (a *App) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError) { - if a.License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { + if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { return "", model.NewAppError("emailToOAuth", "api.user.email_to_oauth.not_available.app_error", nil, "", http.StatusForbidden) } @@ -831,7 +831,7 @@ func (a *App) SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, } func (a *App) SwitchOAuthToEmail(email, password, requesterId string) (string, *model.AppError) { - if a.License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { + if a.Srv().License() != nil && !*a.Config().ServiceSettings.ExperimentalEnableAuthenticationTransfer { return "", model.NewAppError("oauthToEmail", "api.user.oauth_to_email.not_available.app_error", nil, "", http.StatusForbidden) } diff --git a/app/opentracing_layer.go b/app/opentracing_layer.go index c71d68b6d8..4a42971efb 100644 --- a/app/opentracing_layer.go +++ b/app/opentracing_layer.go @@ -11,7 +11,6 @@ import ( "bytes" "context" "crypto/ecdsa" - "html/template" "io" "mime/multipart" "net/http" @@ -171,23 +170,6 @@ func (a *OpenTracingAppLayer) AddDirectChannels(teamId string, user *model.User) return resultVar0 } -func (a *OpenTracingAppLayer) AddLicenseListener(listener func(oldLicense, newLicense *model.License)) string { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddLicenseListener") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.AddLicenseListener(listener) - - return resultVar0 -} - func (a *OpenTracingAppLayer) AddNotificationEmailToBatch(user *model.User, post *model.Post, team *model.Team) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.AddNotificationEmailToBatch") @@ -1296,23 +1278,6 @@ func (a *OpenTracingAppLayer) ClientConfigWithComputed() map[string]string { return resultVar0 } -func (a *OpenTracingAppLayer) ClientLicense() map[string]string { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ClientLicense") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.ClientLicense() - - return resultVar0 -} - func (a *OpenTracingAppLayer) CompareAndDeletePluginKey(pluginId string, key string, oldValue []byte) (bool, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.CompareAndDeletePluginKey") @@ -7298,23 +7263,6 @@ func (a *OpenTracingAppLayer) GetSanitizeOptions(asAdmin bool) map[string]bool { return resultVar0 } -func (a *OpenTracingAppLayer) GetSanitizedClientLicense() map[string]string { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSanitizedClientLicense") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.GetSanitizedClientLicense() - - return resultVar0 -} - func (a *OpenTracingAppLayer) GetSanitizedConfig() *model.Config { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetSanitizedConfig") @@ -8837,23 +8785,6 @@ func (a *OpenTracingAppLayer) GetViewUsersRestrictions(userId string) (*model.Vi return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) HTMLTemplates() *template.Template { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.HTMLTemplates") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.HTMLTemplates() - - return resultVar0 -} - func (a *OpenTracingAppLayer) Handle404(w http.ResponseWriter, r *http.Request) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Handle404") @@ -9218,6 +9149,21 @@ func (a *OpenTracingAppLayer) InitPostMetadata() { a.app.InitPostMetadata() } +func (a *OpenTracingAppLayer) InitServer() { + origCtx := a.ctx + span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InitServer") + + a.ctx = newCtx + a.app.Srv().Store.SetContext(newCtx) + defer func() { + a.app.Srv().Store.SetContext(origCtx) + a.ctx = origCtx + }() + + defer span.Finish() + a.app.InitServer() +} + func (a *OpenTracingAppLayer) InstallMarketplacePlugin(request *model.InstallMarketplacePluginRequest) (*model.Manifest, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InstallMarketplacePlugin") @@ -9299,43 +9245,6 @@ func (a *OpenTracingAppLayer) InstallPluginWithSignature(pluginFile io.ReadSeeke return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) InvalidateAllCaches() *model.AppError { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InvalidateAllCaches") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.InvalidateAllCaches() - - if resultVar0 != nil { - span.LogFields(spanlog.Error(resultVar0)) - ext.Error.Set(span, true) - } - - return resultVar0 -} - -func (a *OpenTracingAppLayer) InvalidateAllCachesSkipSend() { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InvalidateAllCachesSkipSend") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.InvalidateAllCachesSkipSend() -} - func (a *OpenTracingAppLayer) InvalidateAllEmailInvites() *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.InvalidateAllEmailInvites") @@ -9720,23 +9629,6 @@ func (a *OpenTracingAppLayer) LeaveTeam(team *model.Team, user *model.User, requ return resultVar0 } -func (a *OpenTracingAppLayer) License() *model.License { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.License") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.License() - - return resultVar0 -} - func (a *OpenTracingAppLayer) LimitedClientConfig() map[string]string { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LimitedClientConfig") @@ -9883,21 +9775,6 @@ func (a *OpenTracingAppLayer) ListTeamCommands(teamId string) ([]*model.Command, return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) LoadLicense() { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LoadLicense") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.LoadLicense() -} - func (a *OpenTracingAppLayer) LogAuditRec(rec *audit.Record, err error) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.LogAuditRec") @@ -11123,43 +11000,6 @@ func (a *OpenTracingAppLayer) RemoveFile(path string) *model.AppError { return resultVar0 } -func (a *OpenTracingAppLayer) RemoveLicense() *model.AppError { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveLicense") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.RemoveLicense() - - if resultVar0 != nil { - span.LogFields(spanlog.Error(resultVar0)) - ext.Error.Set(span, true) - } - - return resultVar0 -} - -func (a *OpenTracingAppLayer) RemoveLicenseListener(id string) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemoveLicenseListener") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.RemoveLicenseListener(id) -} - func (a *OpenTracingAppLayer) RemovePlugin(id string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RemovePlugin") @@ -11395,28 +11235,6 @@ func (a *OpenTracingAppLayer) RenameTeam(team *model.Team, newTeamName string, n return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) RequestTrialLicense(trialRequest *model.TrialLicenseRequest) *model.AppError { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RequestTrialLicense") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.RequestTrialLicense(trialRequest) - - if resultVar0 != nil { - span.LogFields(spanlog.Error(resultVar0)) - ext.Error.Set(span, true) - } - - return resultVar0 -} - func (a *OpenTracingAppLayer) ResetPasswordFromToken(userSuppliedTokenString string, newPassword string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ResetPasswordFromToken") @@ -11850,28 +11668,6 @@ func (a *OpenTracingAppLayer) SaveConfig(newCfg *model.Config, sendConfigChangeC return resultVar0 } -func (a *OpenTracingAppLayer) SaveLicense(licenseBytes []byte) (*model.License, *model.AppError) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveLicense") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0, resultVar1 := a.app.SaveLicense(licenseBytes) - - if resultVar1 != nil { - span.LogFields(spanlog.Error(resultVar1)) - ext.Error.Set(span, true) - } - - return resultVar0, resultVar1 -} - func (a *OpenTracingAppLayer) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveReactionForPost") @@ -12434,21 +12230,6 @@ func (a *OpenTracingAppLayer) SendAutoResponseIfNecessary(channel *model.Channel return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) SendDailyDiagnostics() { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendDailyDiagnostics") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.SendDailyDiagnostics() -} - func (a *OpenTracingAppLayer) SendDeactivateAccountEmail(email string, locale string, siteURL string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendDeactivateAccountEmail") @@ -12471,21 +12252,6 @@ func (a *OpenTracingAppLayer) SendDeactivateAccountEmail(email string, locale st return resultVar0 } -func (a *OpenTracingAppLayer) SendDiagnostic(event string, properties map[string]interface{}) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendDiagnostic") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.SendDiagnostic(event, properties) -} - func (a *OpenTracingAppLayer) SendEmailVerification(user *model.User, newEmail string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SendEmailVerification") @@ -12949,21 +12715,6 @@ func (a *OpenTracingAppLayer) SetBotIconImageFromMultiPartFile(botUserId string, return resultVar0 } -func (a *OpenTracingAppLayer) SetClientLicense(m map[string]string) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetClientLicense") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.SetClientLicense(m) -} - func (a *OpenTracingAppLayer) SetDefaultProfileImage(user *model.User) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetDefaultProfileImage") @@ -13001,23 +12752,6 @@ func (a *OpenTracingAppLayer) SetDiagnosticId(id string) { a.app.SetDiagnosticId(id) } -func (a *OpenTracingAppLayer) SetLicense(license *model.License) bool { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetLicense") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.SetLicense(license) - - return resultVar0 -} - func (a *OpenTracingAppLayer) SetLog(l *mlog.Logger) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetLog") @@ -13395,43 +13129,6 @@ func (a *OpenTracingAppLayer) SetTeamIconFromMultiPartFile(teamId string, file m return resultVar0 } -func (a *OpenTracingAppLayer) SetupInviteEmailRateLimiting() error { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SetupInviteEmailRateLimiting") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - resultVar0 := a.app.SetupInviteEmailRateLimiting() - - if resultVar0 != nil { - span.LogFields(spanlog.Error(resultVar0)) - ext.Error.Set(span, true) - } - - return resultVar0 -} - -func (a *OpenTracingAppLayer) ShutDownPlugins() { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ShutDownPlugins") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.ShutDownPlugins() -} - func (a *OpenTracingAppLayer) Shutdown() { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.Shutdown") @@ -13589,21 +13286,6 @@ func (a *OpenTracingAppLayer) StartPushNotificationsHubWorkers() { a.app.StartPushNotificationsHubWorkers() } -func (a *OpenTracingAppLayer) StopPushNotificationsHubWorkers() { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.StopPushNotificationsHubWorkers") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.StopPushNotificationsHubWorkers() -} - func (a *OpenTracingAppLayer) SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SubmitInteractiveDialog") @@ -15140,21 +14822,6 @@ func (a *OpenTracingAppLayer) UserIsInAdminRoleGroup(userID string, syncableID s return resultVar0, resultVar1 } -func (a *OpenTracingAppLayer) ValidateAndSetLicenseBytes(b []byte) { - origCtx := a.ctx - span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ValidateAndSetLicenseBytes") - - a.ctx = newCtx - a.app.Srv().Store.SetContext(newCtx) - defer func() { - a.app.Srv().Store.SetContext(origCtx) - a.ctx = origCtx - }() - - defer span.Finish() - a.app.ValidateAndSetLicenseBytes(b) -} - func (a *OpenTracingAppLayer) VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError { origCtx := a.ctx span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.VerifyEmailFromToken") diff --git a/app/options.go b/app/options.go index 560009c76d..5f493db48b 100644 --- a/app/options.go +++ b/app/options.go @@ -105,11 +105,8 @@ func ServerConnector(s *Server) AppOption { a.compliance = s.Compliance a.dataRetention = s.DataRetention a.searchEngine = s.SearchEngine - a.ldap = s.Ldap a.messageExport = s.MessageExport a.metrics = s.Metrics - a.notification = s.Notification - a.saml = s.Saml a.httpService = s.HTTPService a.imageProxy = s.ImageProxy diff --git a/app/plugin.go b/app/plugin.go index cd1377bf84..d2b08b95e1 100644 --- a/app/plugin.go +++ b/app/plugin.go @@ -40,15 +40,24 @@ type pluginSignaturePath struct { // // To get the plugins environment when the plugins are disabled, manually acquire the plugins // lock instead. -func (a *App) GetPluginsEnvironment() *plugin.Environment { - if !*a.Config().PluginSettings.Enable { +func (s *Server) GetPluginsEnvironment() *plugin.Environment { + if !*s.Config().PluginSettings.Enable { return nil } - a.Srv().PluginsLock.RLock() - defer a.Srv().PluginsLock.RUnlock() + s.PluginsLock.RLock() + defer s.PluginsLock.RUnlock() - return a.Srv().PluginsEnvironment + return s.PluginsEnvironment +} + +// GetPluginsEnvironment returns the plugin environment for use if plugins are enabled and +// initialized. +// +// To get the plugins environment when the plugins are disabled, manually acquire the plugins +// lock instead. +func (a *App) GetPluginsEnvironment() *plugin.Environment { + return a.Srv().GetPluginsEnvironment() } func (a *App) SetPluginsEnvironment(pluginsEnvironment *plugin.Environment) { @@ -270,8 +279,8 @@ func (a *App) SyncPlugins() *model.AppError { return nil } -func (a *App) ShutDownPlugins() { - pluginsEnvironment := a.GetPluginsEnvironment() +func (s *Server) ShutDownPlugins() { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return } @@ -280,14 +289,14 @@ func (a *App) ShutDownPlugins() { pluginsEnvironment.Shutdown() - a.RemoveConfigListener(a.Srv().PluginConfigListenerId) - a.Srv().PluginConfigListenerId = "" + s.RemoveConfigListener(s.PluginConfigListenerId) + s.PluginConfigListenerId = "" // Acquiring lock manually before cleaning up PluginsEnvironment. - a.Srv().PluginsLock.Lock() - defer a.Srv().PluginsLock.Unlock() - if a.Srv().PluginsEnvironment == pluginsEnvironment { - a.Srv().PluginsEnvironment = nil + s.PluginsLock.Lock() + defer s.PluginsLock.Unlock() + if s.PluginsEnvironment == pluginsEnvironment { + s.PluginsEnvironment = nil } else { mlog.Warn("Another PluginsEnvironment detected while shutting down plugins.") } @@ -519,7 +528,7 @@ func (a *App) getRemotePlugins() (map[string]*model.MarketplacePlugin, *model.Ap ServerVersion: model.CurrentVersion, } - license := a.License() + license := a.Srv().License() if license != nil && *license.Features.EnterprisePlugins { filter.EnterprisePlugins = true } diff --git a/app/plugin_api.go b/app/plugin_api.go index d8fa9ca47e..47653c4723 100644 --- a/app/plugin_api.go +++ b/app/plugin_api.go @@ -117,7 +117,7 @@ func (api *PluginAPI) GetBundlePath() (string, error) { } func (api *PluginAPI) GetLicense() *model.License { - return api.app.License() + return api.app.Srv().License() } func (api *PluginAPI) GetServerVersion() string { @@ -125,7 +125,7 @@ func (api *PluginAPI) GetServerVersion() string { } func (api *PluginAPI) GetSystemInstallDate() (int64, *model.AppError) { - return api.app.getSystemInstallDate() + return api.app.Srv().getSystemInstallDate() } func (api *PluginAPI) GetDiagnosticId() string { diff --git a/app/plugin_shutdown_test.go b/app/plugin_shutdown_test.go index dddf786c82..a1667b01c7 100644 --- a/app/plugin_shutdown_test.go +++ b/app/plugin_shutdown_test.go @@ -63,7 +63,7 @@ func TestPluginShutdownTest(t *testing.T) { done := make(chan bool) go func() { defer close(done) - th.App.ShutDownPlugins() + th.App.Srv().ShutDownPlugins() }() select { diff --git a/app/plugin_statuses.go b/app/plugin_statuses.go index e6c2486315..6318ef3966 100644 --- a/app/plugin_statuses.go +++ b/app/plugin_statuses.go @@ -10,8 +10,8 @@ import ( ) // GetPluginStatus returns the status for a plugin installed on this server. -func (a *App) GetPluginStatus(id string) (*model.PluginStatus, *model.AppError) { - pluginsEnvironment := a.GetPluginsEnvironment() +func (s *Server) GetPluginStatus(id string) (*model.PluginStatus, *model.AppError) { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return nil, model.NewAppError("GetPluginStatus", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -23,17 +23,22 @@ func (a *App) GetPluginStatus(id string) (*model.PluginStatus, *model.AppError) // Add our cluster ID for _, status := range pluginStatuses { - if status.PluginId == id { - status.ClusterId = a.GetClusterId() + if status.PluginId == id && s.Cluster != nil { + status.ClusterId = s.Cluster.GetClusterId() return status, nil } } return nil, model.NewAppError("GetPluginStatus", "app.plugin.not_installed.app_error", nil, "", http.StatusNotFound) } +// GetPluginStatus returns the status for a plugin installed on this server. +func (a *App) GetPluginStatus(id string) (*model.PluginStatus, *model.AppError) { + return a.Srv().GetPluginStatus(id) +} + // GetPluginStatuses returns the status for plugins installed on this server. -func (a *App) GetPluginStatuses() (model.PluginStatuses, *model.AppError) { - pluginsEnvironment := a.GetPluginsEnvironment() +func (s *Server) GetPluginStatuses() (model.PluginStatuses, *model.AppError) { + pluginsEnvironment := s.GetPluginsEnvironment() if pluginsEnvironment == nil { return nil, model.NewAppError("GetPluginStatuses", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented) } @@ -45,12 +50,21 @@ func (a *App) GetPluginStatuses() (model.PluginStatuses, *model.AppError) { // Add our cluster ID for _, status := range pluginStatuses { - status.ClusterId = a.GetClusterId() + if s.Cluster != nil { + status.ClusterId = s.Cluster.GetClusterId() + } else { + status.ClusterId = "" + } } return pluginStatuses, nil } +// GetPluginStatuses returns the status for plugins installed on this server. +func (a *App) GetPluginStatuses() (model.PluginStatuses, *model.AppError) { + return a.Srv().GetPluginStatuses() +} + // GetClusterPluginStatuses returns the status for plugins installed anywhere in the cluster. func (a *App) GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError) { pluginStatuses, err := a.GetPluginStatuses() diff --git a/app/post.go b/app/post.go index 2ec73840a0..fa05e69fd5 100644 --- a/app/post.go +++ b/app/post.go @@ -194,7 +194,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo post.AddProp("from_bot", "true") } - if a.License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && + if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && !post.IsSystemMessage() && channel.Name == model.DEFAULT_CHANNEL && !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { @@ -406,7 +406,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A } matched := model.AT_MENTION_PATTEN.MatchString(post.Message) - if a.License() != nil && *a.License().Features.LDAPGroups && matched && !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_GROUP_MENTIONS) { + if a.Srv().License() != nil && *a.Srv().License().Features.LDAPGroups && matched && !a.HasPermissionToChannel(post.UserId, post.ChannelId, model.PERMISSION_USE_GROUP_MENTIONS) { post.AddProp(model.POST_PROPS_GROUP_HIGHLIGHT_DISABLED, true) } @@ -533,7 +533,7 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model return nil, err } - if a.License() != nil { + if a.Srv().License() != nil { if *a.Config().ServiceSettings.PostEditTimeLimit != -1 && model.GetMillis() > oldPost.CreateAt+int64(*a.Config().ServiceSettings.PostEditTimeLimit*1000) && post.Message != oldPost.Message { err = model.NewAppError("UpdatePost", "api.post.update_post.permissions_time_limit.app_error", map[string]interface{}{"timeLimit": *a.Config().ServiceSettings.PostEditTimeLimit}, "", http.StatusBadRequest) return nil, err @@ -1120,8 +1120,8 @@ func (a *App) ImageProxyRemover() (f func(string) string) { } } -func (a *App) MaxPostSize() int { - maxPostSize := a.Srv().Store.Post().GetMaxPostSize() +func (s *Server) MaxPostSize() int { + maxPostSize := s.Store.Post().GetMaxPostSize() if maxPostSize == 0 { return model.POST_MESSAGE_MAX_RUNES_V1 } @@ -1129,6 +1129,10 @@ func (a *App) MaxPostSize() int { return maxPostSize } +func (a *App) MaxPostSize() int { + return a.Srv().MaxPostSize() +} + // countMentionsFromPost returns the number of posts in the post's channel that mention the user after and including the // given post. func (a *App) countMentionsFromPost(user *model.User, post *model.Post) (int, *model.AppError) { diff --git a/app/post_test.go b/app/post_test.go index 7a803a8d3f..7e4ebecab6 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -283,7 +283,7 @@ func TestUpdatePostTimeLimit(t *testing.T) { post := &model.Post{} post = th.BasicPost.Clone() - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.PostEditTimeLimit = -1 @@ -1017,7 +1017,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) { } if enableElasticsearch { - th.App.SetLicense(model.NewTestLicense("elastic_search")) + th.App.Srv().SetLicense(model.NewTestLicense("elastic_search")) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ElasticsearchSettings.EnableIndexing = true @@ -1761,7 +1761,7 @@ func TestFillInPostProps(t *testing.T) { t.Run("should not add disable group highlight to post props for user with group mention permissions", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) user1 := th.BasicUser @@ -1815,7 +1815,7 @@ func TestFillInPostProps(t *testing.T) { t.Run("should add disable group highlight to post props for guest user", func(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("ldap")) + th.App.Srv().SetLicense(model.NewTestLicense("ldap")) id := model.NewId() guest := &model.User{ diff --git a/app/reaction.go b/app/reaction.go index d6c89c3e3d..dc3c6cb453 100644 --- a/app/reaction.go +++ b/app/reaction.go @@ -24,7 +24,7 @@ func (a *App) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *m return nil, model.NewAppError("deleteReactionForPost", "api.reaction.save.archived_channel.app_error", nil, "", http.StatusForbidden) } - if a.License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL { + if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL { var user *model.User user, err = a.GetUser(reaction.UserId) if err != nil { @@ -98,7 +98,7 @@ func (a *App) DeleteReactionForPost(reaction *model.Reaction) *model.AppError { return model.NewAppError("deleteReactionForPost", "api.reaction.delete.archived_channel.app_error", nil, "", http.StatusForbidden) } - if a.License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL { + if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL { user, err := a.GetUser(reaction.UserId) if err != nil { return err diff --git a/app/role.go b/app/role.go index 9cad4d098a..2de152be77 100644 --- a/app/role.go +++ b/app/role.go @@ -20,13 +20,13 @@ func (a *App) GetAllRoles() ([]*model.Role, *model.AppError) { return a.Srv().Store.Role().GetAll() } -func (a *App) GetRoleByName(name string) (*model.Role, *model.AppError) { - role, err := a.Srv().Store.Role().GetByName(name) +func (s *Server) GetRoleByName(name string) (*model.Role, *model.AppError) { + role, err := s.Store.Role().GetByName(name) if err != nil { return nil, err } - err = a.mergeChannelHigherScopedPermissions([]*model.Role{role}) + err = s.mergeChannelHigherScopedPermissions([]*model.Role{role}) if err != nil { return nil, err } @@ -34,6 +34,10 @@ func (a *App) GetRoleByName(name string) (*model.Role, *model.AppError) { return role, nil } +func (a *App) GetRoleByName(name string) (*model.Role, *model.AppError) { + return a.Srv().GetRoleByName(name) +} + func (a *App) GetRolesByNames(names []string) ([]*model.Role, *model.AppError) { roles, err := a.Srv().Store.Role().GetByNames(names) if err != nil { @@ -50,7 +54,7 @@ func (a *App) GetRolesByNames(names []string) ([]*model.Role, *model.AppError) { // mergeChannelHigherScopedPermissions updates the permissions based on the role type, whether the permission is // moderated, and the value of the permission on the higher-scoped scheme. -func (a *App) mergeChannelHigherScopedPermissions(roles []*model.Role) *model.AppError { +func (s *Server) mergeChannelHigherScopedPermissions(roles []*model.Role) *model.AppError { var higherScopeNamesToQuery []string for _, role := range roles { @@ -63,7 +67,7 @@ func (a *App) mergeChannelHigherScopedPermissions(roles []*model.Role) *model.Ap return nil } - higherScopedPermissionsMap, err := a.Srv().Store.Role().ChannelHigherScopedPermissions(higherScopeNamesToQuery) + higherScopedPermissionsMap, err := s.Store.Role().ChannelHigherScopedPermissions(higherScopeNamesToQuery) if err != nil { return err } @@ -79,6 +83,12 @@ func (a *App) mergeChannelHigherScopedPermissions(roles []*model.Role) *model.Ap return nil } +// mergeChannelHigherScopedPermissions updates the permissions based on the role type, whether the permission is +// moderated, and the value of the permission on the higher-scoped scheme. +func (a *App) mergeChannelHigherScopedPermissions(roles []*model.Role) *model.AppError { + return a.Srv().mergeChannelHigherScopedPermissions(roles) +} + func (a *App) PatchRole(role *model.Role, patch *model.RolePatch) (*model.Role, *model.AppError) { // If patch is a no-op then short-circuit the store. if patch.Permissions != nil && reflect.DeepEqual(*patch.Permissions, role.Permissions) { diff --git a/app/role_test.go b/app/role_test.go index d9fdaae7c0..eda886fd2f 100644 --- a/app/role_test.go +++ b/app/role_test.go @@ -54,7 +54,7 @@ func testPermissionInheritance(t *testing.T, testCallback func(t *testing.T, th th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense("")) + th.App.Srv().SetLicense(model.NewTestLicense("")) th.App.SetPhase2PermissionsMigrationStatus(true) permissionsDefault := []string{ diff --git a/app/scheme.go b/app/scheme.go index 2cccee1638..2448dacd69 100644 --- a/app/scheme.go +++ b/app/scheme.go @@ -33,12 +33,16 @@ func (a *App) GetSchemesPage(scope string, page int, perPage int) ([]*model.Sche return a.GetSchemes(scope, page*perPage, perPage) } -func (a *App) GetSchemes(scope string, offset int, limit int) ([]*model.Scheme, *model.AppError) { - if err := a.IsPhase2MigrationCompleted(); err != nil { +func (s *Server) GetSchemes(scope string, offset int, limit int) ([]*model.Scheme, *model.AppError) { + if err := s.IsPhase2MigrationCompleted(); err != nil { return nil, err } - return a.Srv().Store.Scheme().GetAllPage(scope, offset, limit) + return s.Store.Scheme().GetAllPage(scope, offset, limit) +} + +func (a *App) GetSchemes(scope string, offset int, limit int) ([]*model.Scheme, *model.AppError) { + return a.Srv().GetSchemes(scope, offset, limit) } func (a *App) CreateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError) { @@ -125,20 +129,24 @@ func (a *App) GetChannelsForScheme(scheme *model.Scheme, offset int, limit int) return a.Srv().Store.Channel().GetChannelsByScheme(scheme.Id, offset, limit) } -func (a *App) IsPhase2MigrationCompleted() *model.AppError { - if a.Srv().phase2PermissionsMigrationComplete { +func (s *Server) IsPhase2MigrationCompleted() *model.AppError { + if s.phase2PermissionsMigrationComplete { return nil } - if _, err := a.Srv().Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil { + if _, err := s.Store.System().GetByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2); err != nil { return model.NewAppError("App.IsPhase2MigrationCompleted", "app.schemes.is_phase_2_migration_completed.not_completed.app_error", nil, err.Error(), http.StatusNotImplemented) } - a.Srv().phase2PermissionsMigrationComplete = true + s.phase2PermissionsMigrationComplete = true return nil } +func (a *App) IsPhase2MigrationCompleted() *model.AppError { + return a.Srv().IsPhase2MigrationCompleted() +} + func (a *App) SchemesIterator(scope string, batchSize int) func() []*model.Scheme { offset := 0 return func() []*model.Scheme { diff --git a/app/server.go b/app/server.go index a3a8c56566..312059c4a4 100644 --- a/app/server.go +++ b/app/server.go @@ -53,9 +53,10 @@ import ( var MaxNotificationsPerChannelDefault int64 = 1000000 type Server struct { - sqlStore *sqlstore.SqlSupplier - Store store.Store - WebSocketRouter *WebSocketRouter + sqlStore *sqlstore.SqlSupplier + Store store.Store + WebSocketRouter *WebSocketRouter + AppInitializedOnce sync.Once // RootRouter is the starting point for all HTTP requests to the server. RootRouter *mux.Router @@ -345,33 +346,19 @@ func NewServer(options ...Option) (*Server, error) { mlog.Error("Error to reset the server status.", mlog.Err(err)) } - // Scheduler must be started before cluster. - s.initJobs() - - if s.joinCluster && s.Cluster != nil { - s.FakeApp().registerAllClusterMessageHandlers() - s.Cluster.StartInterNodeCommunication() - } - if s.startMetrics && s.Metrics != nil { s.Metrics.StartServer() } - s.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) { - if *oldConfig.GuestAccountsSettings.Enable && !*newConfig.GuestAccountsSettings.Enable { - if appErr := s.FakeApp().DeactivateGuests(); appErr != nil { - mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) - } - } - }) + s.SearchEngine.UpdateConfig(s.Config()) + searchConfigListenerId, searchLicenseListenerId := s.StartSearchEngine() + s.searchConfigListenerId = searchConfigListenerId + s.searchLicenseListenerId = searchLicenseListenerId - // Disable active guest accounts on first run if guest accounts are disabled - if !*s.Config().GuestAccountsSettings.Enable { - if appErr := s.FakeApp().DeactivateGuests(); appErr != nil { - mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr)) - } - } + return s, nil +} +func (s *Server) RunJobs() { if s.runjobs { s.Go(func() { runSecurityJob(s) @@ -388,9 +375,6 @@ func NewServer(options ...Option) (*Server, error) { s.Go(func() { runCommandWebhookCleanupJob(s) }) - s.Go(func() { - runLicenseExpirationCheckJob(s) - }) if complianceI := s.Compliance; complianceI != nil { complianceI.StartComplianceDailyJob() @@ -403,13 +387,6 @@ func NewServer(options ...Option) (*Server, error) { s.Jobs.StartSchedulers() } } - - s.SearchEngine.UpdateConfig(s.Config()) - searchConfigListenerId, searchLicenseListenerId := s.StartSearchEngine() - s.searchConfigListenerId = searchConfigListenerId - s.searchLicenseListenerId = searchLicenseListenerId - - return s, nil } // Global app options that should be applied to apps created by this server @@ -448,7 +425,11 @@ func (s *Server) Shutdown() error { defer sentry.Flush(2 * time.Second) - s.RunOldAppShutdown() + s.HubStop() + s.StopPushNotificationsHubWorkers() + s.ShutDownPlugins() + s.RemoveLicenseListener(s.licenseListenerId) + s.RemoveClusterLeaderChangedListener(s.clusterLeaderListenerId) if s.tracer != nil { if err := s.tracer.Close(); err != nil { @@ -842,10 +823,10 @@ func doDiagnosticsIfNeeded(s *Server, firstRun time.Time) { func runDiagnosticsJob(s *Server) { // Send on boot doDiagnostics(s) - firstRun, err := s.FakeApp().getFirstServerRunTimestamp() + firstRun, err := s.getFirstServerRunTimestamp() if err != nil { mlog.Warn("Fetching time of first server run failed. Setting to 'now'.") - s.FakeApp().ensureFirstServerRunTimestamp() + s.ensureFirstServerRunTimestamp() firstRun = utils.MillisFromTime(time.Now()) } model.CreateRecurringTask("Diagnostics", func() { @@ -874,10 +855,10 @@ func runSessionCleanupJob(s *Server) { }, time.Hour*24) } -func runLicenseExpirationCheckJob(s *Server) { - doLicenseExpirationCheck(s) +func runLicenseExpirationCheckJob(a *App) { + doLicenseExpirationCheck(a) model.CreateRecurringTask("License Expiration Check", func() { - doLicenseExpirationCheck(s) + doLicenseExpirationCheck(a) }, time.Hour*24) } @@ -888,7 +869,7 @@ func doSecurity(s *Server) { func doDiagnostics(s *Server) { if *s.Config().LogSettings.EnableDiagnostics { s.timestampLastDiagnosticSent = time.Now() - s.FakeApp().SendDailyDiagnostics() + s.SendDailyDiagnostics() } } @@ -908,9 +889,9 @@ func doSessionCleanup(s *Server) { s.Store.Session().Cleanup(model.GetMillis(), SESSIONS_CLEANUP_BATCH_SIZE) } -func doLicenseExpirationCheck(s *Server) { - s.FakeApp().LoadLicense() - license := s.License() +func doLicenseExpirationCheck(a *App) { + a.Srv().LoadLicense() + license := a.Srv().License() if license == nil { mlog.Debug("License cannot be found.") @@ -922,7 +903,7 @@ func doLicenseExpirationCheck(s *Server) { return } - users, err := s.Store.User().GetSystemAdminProfiles() + users, err := a.Srv().Store.User().GetSystemAdminProfiles() if err != nil { mlog.Error("Failed to get system admins for license expired message from Mattermost.") return @@ -937,15 +918,15 @@ func doLicenseExpirationCheck(s *Server) { } mlog.Debug("Sending license expired email.", mlog.String("user_email", user.Email)) - s.Go(func() { - if err := s.FakeApp().SendRemoveExpiredLicenseEmail(user.Email, user.Locale, *s.Config().ServiceSettings.SiteURL, license.Id); err != nil { + a.Srv().Go(func() { + if err := a.SendRemoveExpiredLicenseEmail(user.Email, user.Locale, *a.Config().ServiceSettings.SiteURL, license.Id); err != nil { mlog.Error("Error while sending the license expired email.", mlog.String("user_email", user.Email), mlog.Err(err)) } }) } //remove the license - s.FakeApp().RemoveLicense() + a.Srv().RemoveLicense() } func (s *Server) StartSearchEngine() (string, string) { @@ -1159,3 +1140,30 @@ func (s *Server) ensureDiagnosticId() { s.diagnosticId = id } + +func (s *Server) configOrLicenseListener() { + s.regenerateClientConfig() +} + +func (s *Server) ClientConfigHash() string { + return s.clientConfigHash.Load().(string) +} + +func (s *Server) initJobs() { + s.Jobs = jobs.NewJobServer(s, s.Store) + if jobsDataRetentionJobInterface != nil { + s.Jobs.DataRetentionJob = jobsDataRetentionJobInterface(s) + } + if jobsMessageExportJobInterface != nil { + s.Jobs.MessageExportJob = jobsMessageExportJobInterface(s) + } + if jobsElasticsearchAggregatorInterface != nil { + s.Jobs.ElasticsearchAggregator = jobsElasticsearchAggregatorInterface(s) + } + if jobsElasticsearchIndexerInterface != nil { + s.Jobs.ElasticsearchIndexer = jobsElasticsearchIndexerInterface(s) + } + if jobsBleveIndexerInterface != nil { + s.Jobs.BleveIndexer = jobsBleveIndexerInterface(s) + } +} diff --git a/app/server_app_adapters.go b/app/server_app_adapters.go index 10429b3a81..803482cd0f 100644 --- a/app/server_app_adapters.go +++ b/app/server_app_adapters.go @@ -24,34 +24,34 @@ import ( // Don't add anything new here, new initialization should be done in the server and // performed in the NewServer function. func (s *Server) RunOldAppInitialization() error { - s.FakeApp().createPushNotificationsHub() + s.createPushNotificationsHub() if err := utils.InitTranslations(s.Config().LocalizationSettings); err != nil { return errors.Wrapf(err, "unable to load Mattermost translation files") } s.configListenerId = s.AddConfigListener(func(_, _ *model.Config) { - s.FakeApp().configOrLicenseListener() + s.configOrLicenseListener() message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CONFIG_CHANGED, "", "", "", nil) - message.Add("config", s.FakeApp().ClientConfigWithComputed()) + message.Add("config", s.ClientConfigWithComputed()) s.Go(func() { - s.FakeApp().Publish(message) + s.Publish(message) }) }) s.licenseListenerId = s.AddLicenseListener(func(oldLicense, newLicense *model.License) { - s.FakeApp().configOrLicenseListener() + s.configOrLicenseListener() message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_LICENSE_CHANGED, "", "", "", nil) - message.Add("license", s.FakeApp().GetSanitizedClientLicense()) + message.Add("license", s.GetSanitizedClientLicense()) s.Go(func() { - s.FakeApp().Publish(message) + s.Publish(message) }) }) - if err := s.FakeApp().SetupInviteEmailRateLimiting(); err != nil { + if err := s.setupInviteEmailRateLimiting(); err != nil { return err } @@ -96,31 +96,40 @@ func (s *Server) RunOldAppInitialization() error { } s.Store = s.newStore() - s.FakeApp().StartPushNotificationsHubWorkers() - if err := s.FakeApp().ensureAsymmetricSigningKey(); err != nil { + if model.BuildEnterpriseReady == "true" { + s.LoadLicense() + } + + s.initJobs() + + if s.joinCluster && s.Cluster != nil { + s.Cluster.StartInterNodeCommunication() + } + + if err := s.ensureAsymmetricSigningKey(); err != nil { return errors.Wrapf(err, "unable to ensure asymmetric signing key") } - if err := s.FakeApp().ensurePostActionCookieSecret(); err != nil { + if err := s.ensurePostActionCookieSecret(); err != nil { return errors.Wrapf(err, "unable to ensure PostAction cookie secret") } - if err := s.FakeApp().ensureInstallationDate(); err != nil { + if err := s.ensureInstallationDate(); err != nil { return errors.Wrapf(err, "unable to ensure installation date") } - if err := s.FakeApp().ensureFirstServerRunTimestamp(); err != nil { + if err := s.ensureFirstServerRunTimestamp(); err != nil { return errors.Wrapf(err, "unable to ensure first run timestamp") } s.ensureDiagnosticId() - s.FakeApp().regenerateClientConfig() + s.regenerateClientConfig() s.clusterLeaderListenerId = s.AddClusterLeaderChangedListener(func() { - mlog.Info("Cluster leader changed. Determining if job schedulers should be running:", mlog.Bool("isLeader", s.FakeApp().IsLeader())) + mlog.Info("Cluster leader changed. Determining if job schedulers should be running:", mlog.Bool("isLeader", s.IsLeader())) if s.Jobs != nil && s.Jobs.Schedulers != nil { - s.Jobs.Schedulers.HandleClusterLeaderChange(s.FakeApp().IsLeader()) + s.Jobs.Schedulers.HandleClusterLeaderChange(s.IsLeader()) } }) @@ -129,10 +138,6 @@ func (s *Server) RunOldAppInitialization() error { return errors.Wrap(err, "failed to parse SiteURL subpath") } s.Router = s.RootRouter.PathPrefix(subpath).Subrouter() - pluginsRoute := s.Router.PathPrefix("/plugins/{plugin_id:[A-Za-z0-9\\_\\-\\.]+}").Subrouter() - pluginsRoute.HandleFunc("", s.FakeApp().ServePluginRequest) - pluginsRoute.HandleFunc("/public/{public_file:.*}", s.FakeApp().ServePluginPublicRequest) - pluginsRoute.HandleFunc("/{anything:.*}", s.FakeApp().ServePluginRequest) // If configured with a subpath, redirect 404s at the root back into the subpath. if subpath != "/" { @@ -141,10 +146,9 @@ func (s *Server) RunOldAppInitialization() error { http.Redirect(w, r, r.URL.String(), http.StatusFound) }) } - s.Router.NotFoundHandler = http.HandlerFunc(s.FakeApp().Handle404) s.WebSocketRouter = &WebSocketRouter{ - app: s.FakeApp(), + server: s, handlers: make(map[string]webSocketHandler), } @@ -164,39 +168,5 @@ func (s *Server) RunOldAppInitialization() error { mlog.Error("Problem with file storage settings", mlog.Err(appErr)) } - if model.BuildEnterpriseReady == "true" { - s.FakeApp().LoadLicense() - } - - s.FakeApp().DoAppMigrations() - - s.FakeApp().InitPostMetadata() - - s.FakeApp().InitPlugins(*s.Config().PluginSettings.Directory, *s.Config().PluginSettings.ClientDirectory) - s.FakeApp().AddConfigListener(func(prevCfg, cfg *model.Config) { - if *cfg.PluginSettings.Enable { - s.FakeApp().InitPlugins(*cfg.PluginSettings.Directory, *s.Config().PluginSettings.ClientDirectory) - } else { - s.FakeApp().ShutDownPlugins() - } - }) - return nil } - -func (s *Server) RunOldAppShutdown() { - s.FakeApp().HubStop() - s.FakeApp().StopPushNotificationsHubWorkers() - s.FakeApp().ShutDownPlugins() - s.FakeApp().RemoveLicenseListener(s.licenseListenerId) - s.RemoveClusterLeaderChangedListener(s.clusterLeaderListenerId) -} - -// A temporary bridge to deal with cases where the code is so tighly coupled that -// this is easier as a temporary solution -func (s *Server) FakeApp() *App { - a := New( - ServerConnector(s), - ) - return a -} diff --git a/app/session_test.go b/app/session_test.go index 138e7f032f..ea6ed8f45c 100644 --- a/app/session_test.go +++ b/app/session_test.go @@ -60,7 +60,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { session, _ = th.App.CreateSession(session) - th.App.SetLicense(model.NewTestLicense("compliance")) + th.App.Srv().SetLicense(model.NewTestLicense("compliance")) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SessionIdleTimeoutInMinutes = 5 }) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExtendSessionLengthWithActivity = false }) @@ -110,7 +110,7 @@ func TestGetSessionIdleTimeoutInMinutes(t *testing.T) { _, err = th.App.GetSession(session.Token) assert.Nil(t, err) - th.App.SetLicense(model.NewTestLicense("compliance")) + th.App.Srv().SetLicense(model.NewTestLicense("compliance")) // Test regular session with timeout set to 0, should not timeout th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SessionIdleTimeoutInMinutes = 0 }) @@ -133,7 +133,7 @@ func TestUpdateSessionOnPromoteDemote(t *testing.T) { th := Setup(t).InitBasic() defer th.TearDown() - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) t.Run("Promote Guest to User updates the session", func(t *testing.T) { guest := th.CreateGuest() diff --git a/app/slackimport.go b/app/slackimport.go index c4238445b8..75c64c0130 100644 --- a/app/slackimport.go +++ b/app/slackimport.go @@ -751,7 +751,7 @@ func (a *App) SlackImport(fileData multipart.File, fileSize int64, teamID string a.deactivateSlackBotUser(botUser) } - a.InvalidateAllCaches() + a.Srv().InvalidateAllCaches() log.WriteString(utils.T("api.slackimport.slack_import.notes")) log.WriteString("=======\r\n\r\n") diff --git a/app/user.go b/app/user.go index 5fd8dcc042..3cbb109bcf 100644 --- a/app/user.go +++ b/app/user.go @@ -191,9 +191,13 @@ func (a *App) IsUserSignUpAllowed() *model.AppError { return nil } -func (a *App) IsFirstUserAccount() bool { - if a.SessionCacheLength() == 0 { - count, err := a.Srv().Store.User().Count(model.UserCountOptions{IncludeDeleted: true}) +func (s *Server) IsFirstUserAccount() bool { + cachedSessions, err := s.sessionCache.Len() + if err != nil { + return false + } + if cachedSessions == 0 { + count, err := s.Store.User().Count(model.UserCountOptions{IncludeDeleted: true}) if err != nil { mlog.Error("There was a error fetching if first user account", mlog.Err(err)) return false @@ -206,6 +210,10 @@ func (a *App) IsFirstUserAccount() bool { return false } +func (a *App) IsFirstUserAccount() bool { + return a.Srv().IsFirstUserAccount() +} + // CreateUser creates a user and sets several fields of the returned User struct to // their zero values. func (a *App) CreateUser(user *model.User) (*model.User, *model.AppError) { diff --git a/app/web_conn.go b/app/web_conn.go index dbae9703db..6082751a4d 100644 --- a/app/web_conn.go +++ b/app/web_conn.go @@ -286,7 +286,7 @@ func (wc *WebConn) IsAuthenticated() bool { func (wc *WebConn) createHelloMessage() *model.WebSocketEvent { msg := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_HELLO, "", "", wc.UserId, nil) - msg.Add("server_version", fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, wc.App.ClientConfigHash(), wc.App.License() != nil)) + msg.Add("server_version", fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, wc.App.ClientConfigHash(), wc.App.Srv().License() != nil)) return msg } diff --git a/app/web_hub.go b/app/web_hub.go index d5deaadb16..38f5858b41 100644 --- a/app/web_hub.go +++ b/app/web_hub.go @@ -96,19 +96,6 @@ func (a *App) HubStart() { } } -func (a *App) PublishSkipClusterSend(message *model.WebSocketEvent) { - if message.GetBroadcast().UserId != "" { - hub := a.GetHubForUserId(message.GetBroadcast().UserId) - if hub != nil { - hub.Broadcast(message) - } - return - } - for _, hub := range a.Srv().GetHubs() { - hub.Broadcast(message) - } -} - func (a *App) invalidateCacheForUserSkipClusterSend(userId string) { a.Srv().Store.Channel().InvalidateAllChannelMembersForUser(userId) a.InvalidateWebConnSessionCacheForUser(userId) @@ -126,26 +113,30 @@ func (a *App) InvalidateWebConnSessionCacheForUser(userId string) { } // HubStop stops all the hubs. -func (a *App) HubStop() { +func (s *Server) HubStop() { mlog.Info("stopping websocket hub connections") - for _, hub := range a.Srv().GetHubs() { + for _, hub := range s.GetHubs() { hub.Stop() } - a.Srv().SetHubs([]*Hub{}) + s.SetHubs([]*Hub{}) +} + +func (a *App) HubStop() { + a.Srv().HubStop() } // GetHubForUserId returns the hub for a given user id. -func (a *App) GetHubForUserId(userId string) *Hub { - if len(a.Srv().GetHubs()) == 0 { +func (s *Server) GetHubForUserId(userId string) *Hub { + if len(s.GetHubs()) == 0 { return nil } hash := fnv.New32a() hash.Write([]byte(userId)) - index := hash.Sum32() % uint32(len(a.Srv().GetHubs())) - hub, err := a.Srv().GetHub(int(index)) + index := hash.Sum32() % uint32(len(s.GetHubs())) + hub, err := s.GetHub(int(index)) if err != nil { mlog.Warn("Requested hub doesn't exist", mlog.Int("hub_index", int(index))) return nil @@ -153,6 +144,10 @@ func (a *App) GetHubForUserId(userId string) *Hub { return hub } +func (a *App) GetHubForUserId(userId string) *Hub { + return a.Srv().GetHubForUserId(userId) +} + // HubRegister registers a connection to a hub. func (a *App) HubRegister(webConn *WebConn) { hub := a.GetHubForUserId(webConn.UserId) @@ -175,14 +170,14 @@ func (a *App) HubUnregister(webConn *WebConn) { } } -func (a *App) Publish(message *model.WebSocketEvent) { - if metrics := a.Metrics(); metrics != nil { - metrics.IncrementWebsocketEvent(message.EventType()) +func (s *Server) Publish(message *model.WebSocketEvent) { + if s.Metrics != nil { + s.Metrics.IncrementWebsocketEvent(message.EventType()) } - a.PublishSkipClusterSend(message) + s.PublishSkipClusterSend(message) - if a.Cluster() != nil { + if s.Cluster != nil { cm := &model.ClusterMessage{ Event: model.CLUSTER_EVENT_PUBLISH, SendType: model.CLUSTER_SEND_BEST_EFFORT, @@ -197,10 +192,31 @@ func (a *App) Publish(message *model.WebSocketEvent) { cm.SendType = model.CLUSTER_SEND_RELIABLE } - a.Cluster().SendClusterMessage(cm) + s.Cluster.SendClusterMessage(cm) } } +func (a *App) Publish(message *model.WebSocketEvent) { + a.Srv().Publish(message) +} + +func (s *Server) PublishSkipClusterSend(message *model.WebSocketEvent) { + if message.GetBroadcast().UserId != "" { + hub := s.GetHubForUserId(message.GetBroadcast().UserId) + if hub != nil { + hub.Broadcast(message) + } + } else { + for _, hub := range s.GetHubs() { + hub.Broadcast(message) + } + } +} + +func (a *App) PublishSkipClusterSend(message *model.WebSocketEvent) { + a.Srv().PublishSkipClusterSend(message) +} + func (a *App) invalidateCacheForChannel(channel *model.Channel) { a.Srv().Store.Channel().InvalidateChannel(channel.Id) a.invalidateCacheForChannelByNameSkipClusterSend(channel.TeamId, channel.Name) diff --git a/app/webhook.go b/app/webhook.go index 9731d8177d..46989d34c5 100644 --- a/app/webhook.go +++ b/app/webhook.go @@ -673,7 +673,7 @@ func (a *App) HandleIncomingWebhook(hookId string, req *model.IncomingWebhookReq user = result.Data.(*model.User) } - if a.License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && + if a.Srv().License() != nil && *a.Config().TeamSettings.ExperimentalTownSquareIsReadOnly && channel.Name == model.DEFAULT_CHANNEL && !a.RolesGrantPermission(user.GetRoles(), model.PERMISSION_MANAGE_SYSTEM.Id) { return model.NewAppError("HandleIncomingWebhook", "api.post.create_post.town_square_read_only", nil, "", http.StatusForbidden) } diff --git a/app/websocket_router.go b/app/websocket_router.go index 0aab6d2dc7..179382daf1 100644 --- a/app/websocket_router.go +++ b/app/websocket_router.go @@ -16,6 +16,7 @@ type webSocketHandler interface { } type WebSocketRouter struct { + server *Server app *App handlers map[string]webSocketHandler } @@ -25,6 +26,9 @@ func (wr *WebSocketRouter) Handle(action string, handler webSocketHandler) { } func (wr *WebSocketRouter) ServeWebSocket(conn *WebConn, r *model.WebSocketRequest) { + wr.app = New(ServerConnector(wr.server)) + wr.app.InitServer() + if r.Action == "" { err := model.NewAppError("ServeWebSocket", "api.web_socket_router.no_action.app_error", nil, "", http.StatusBadRequest) returnWebSocketError(wr.app, conn, r, err) diff --git a/cmd/mattermost/commands/cmdtestlib.go b/cmd/mattermost/commands/cmdtestlib.go index e019f9fd54..d936d1f473 100644 --- a/cmd/mattermost/commands/cmdtestlib.go +++ b/cmd/mattermost/commands/cmdtestlib.go @@ -19,6 +19,7 @@ import ( "github.com/mattermost/mattermost-server/v5/api4" "github.com/mattermost/mattermost-server/v5/model" + "github.com/mattermost/mattermost-server/v5/store/storetest/mocks" "github.com/mattermost/mattermost-server/v5/testlib" ) @@ -65,6 +66,12 @@ func SetupWithStoreMock(t testing.TB) *testHelper { } api4TestHelper := api4.SetupWithStoreMock(t) + systemStore := mocks.SystemStore{} + systemStore.On("Get").Return(make(model.StringMap), nil) + licenseStore := mocks.LicenseStore{} + licenseStore.On("Get", "").Return(&model.LicenseRecord{}, nil) + api4TestHelper.App.Srv().Store.(*mocks.Store).On("System").Return(&systemStore) + api4TestHelper.App.Srv().Store.(*mocks.Store).On("License").Return(&licenseStore) testHelper := &testHelper{ TestHelper: api4TestHelper, diff --git a/cmd/mattermost/commands/export.go b/cmd/mattermost/commands/export.go index 076cc19142..f3a46a11fa 100644 --- a/cmd/mattermost/commands/export.go +++ b/cmd/mattermost/commands/export.go @@ -145,7 +145,7 @@ func scheduleExportCmdF(command *cobra.Command, args []string) error { func buildExportCmdF(format string) func(command *cobra.Command, args []string) error { return func(command *cobra.Command, args []string) error { a, err := InitDBCommandContextCobra(command) - license := a.License() + license := a.Srv().License() if err != nil { return err } diff --git a/cmd/mattermost/commands/init.go b/cmd/mattermost/commands/init.go index e4bec66fb4..effa626cb9 100644 --- a/cmd/mattermost/commands/init.go +++ b/cmd/mattermost/commands/init.go @@ -41,10 +41,10 @@ func InitDBCommandContext(configDSN string) (*app.App, error) { return nil, err } - a := s.FakeApp() + a := app.New(app.ServerConnector(s)) if model.BuildEnterpriseReady == "true" { - a.LoadLicense() + a.Srv().LoadLicense() } return a, nil diff --git a/cmd/mattermost/commands/jobserver.go b/cmd/mattermost/commands/jobserver.go index 8ff3282e21..a7a212ba36 100644 --- a/cmd/mattermost/commands/jobserver.go +++ b/cmd/mattermost/commands/jobserver.go @@ -41,7 +41,7 @@ func jobserverCmdF(command *cobra.Command, args []string) error { } defer a.Shutdown() - a.LoadLicense() + a.Srv().LoadLicense() // Run jobs mlog.Info("Starting Mattermost job server") diff --git a/cmd/mattermost/commands/license.go b/cmd/mattermost/commands/license.go index c6661e7bc0..8deffc4387 100644 --- a/cmd/mattermost/commands/license.go +++ b/cmd/mattermost/commands/license.go @@ -45,7 +45,7 @@ func uploadLicenseCmdF(command *cobra.Command, args []string) error { return err } - if _, err := a.SaveLicense(fileBytes); err != nil { + if _, err := a.Srv().SaveLicense(fileBytes); err != nil { return err } diff --git a/cmd/mattermost/commands/permissions.go b/cmd/mattermost/commands/permissions.go index 502aa7a2b8..a10bdf5dd6 100644 --- a/cmd/mattermost/commands/permissions.go +++ b/cmd/mattermost/commands/permissions.go @@ -100,7 +100,7 @@ func exportPermissionsCmdF(command *cobra.Command, args []string) error { } defer a.Shutdown() - if license := a.License(); license == nil { + if license := a.Srv().License(); license == nil { return errors.New(utils.T("cli.license.critical")) } @@ -121,7 +121,7 @@ func importPermissionsCmdF(command *cobra.Command, args []string) error { } defer a.Shutdown() - if license := a.License(); license == nil { + if license := a.Srv().License(); license == nil { return errors.New(utils.T("cli.license.critical")) } diff --git a/cmd/mattermost/commands/server.go b/cmd/mattermost/commands/server.go index 63e86b34f7..66f47408cb 100644 --- a/cmd/mattermost/commands/server.go +++ b/cmd/mattermost/commands/server.go @@ -73,7 +73,7 @@ func runServer(configStore config.Store, disableConfigWatch bool, usedPlatform b } api := api4.Init(server, server.AppOptions, server.Router) - wsapi.Init(server.FakeApp(), server.WebSocketRouter) + wsapi.Init(server) web.New(server, server.AppOptions, server.Router) api4.InitLocal(server, server.AppOptions, server.LocalRouter) diff --git a/cmd/mattermost/commands/test.go b/cmd/mattermost/commands/test.go index bfc5404eb9..d4a982fb20 100644 --- a/cmd/mattermost/commands/test.go +++ b/cmd/mattermost/commands/test.go @@ -59,7 +59,7 @@ func webClientTestsCmdF(command *cobra.Command, args []string) error { } api4.Init(a, a.Srv().AppOptions, a.Srv().Router) - wsapi.Init(a, a.Srv().WebSocketRouter) + wsapi.Init(a.Srv()) a.UpdateConfig(setupClientTests) runWebClientTests() @@ -80,7 +80,7 @@ func serverForWebClientTestsCmdF(command *cobra.Command, args []string) error { } api4.Init(a, a.Srv().AppOptions, a.Srv().Router) - wsapi.Init(a, a.Srv().WebSocketRouter) + wsapi.Init(a.Srv()) a.UpdateConfig(setupClientTests) c := make(chan os.Signal, 1) diff --git a/migrations/helper_test.go b/migrations/helper_test.go index e35c587911..89c6463206 100644 --- a/migrations/helper_test.go +++ b/migrations/helper_test.go @@ -50,7 +50,7 @@ func setupTestHelper(enterprise bool) *TestHelper { s.Store = localcachelayer.NewLocalCacheLayer(s.Store, s.Metrics, s.Cluster, s.CacheProvider) th := &TestHelper{ - App: s.FakeApp(), + App: app.New(app.ServerConnector(s)), Server: s, } @@ -73,9 +73,9 @@ func setupTestHelper(enterprise bool) *TestHelper { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) if enterprise { - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) } else { - th.App.SetLicense(nil) + th.App.Srv().SetLicense(nil) } return th @@ -248,7 +248,7 @@ func (me *TestHelper) AddUserToChannel(user *model.User, channel *model.Channel) func (me *TestHelper) TearDown() { // Clean all the caches - me.App.InvalidateAllCaches() + me.App.Srv().InvalidateAllCaches() me.Server.Shutdown() if me.tempWorkspace != "" { os.RemoveAll(me.tempWorkspace) diff --git a/services/searchengine/bleveengine/indexer/indexing_job.go b/services/searchengine/bleveengine/indexer/indexing_job.go index 7d474e8f7e..94d4872176 100644 --- a/services/searchengine/bleveengine/indexer/indexing_job.go +++ b/services/searchengine/bleveengine/indexer/indexing_job.go @@ -46,6 +46,9 @@ type BleveIndexerWorker struct { } func (bi *BleveIndexerInterfaceImpl) MakeWorker() model.Worker { + if bi.Server.SearchEngine.BleveEngine == nil { + return nil + } return &BleveIndexerWorker{ name: "BleveIndexer", stop: make(chan bool, 1), diff --git a/web/context.go b/web/context.go index 68a4bcdda2..fc66e7adfa 100644 --- a/web/context.go +++ b/web/context.go @@ -141,7 +141,7 @@ func (c *Context) SessionRequired() { func (c *Context) MfaRequired() { // Must be licensed for MFA and have it configured for enforcement - if license := c.App.License(); license == nil || !*license.Features.MFA || !*c.App.Config().ServiceSettings.EnableMultifactorAuthentication || !*c.App.Config().ServiceSettings.EnforceMultifactorAuthentication { + if license := c.App.Srv().License(); license == nil || !*license.Features.MFA || !*c.App.Config().ServiceSettings.EnableMultifactorAuthentication || !*c.App.Config().ServiceSettings.EnforceMultifactorAuthentication { return } diff --git a/web/handlers.go b/web/handlers.go index effb391587..a0e8218db2 100644 --- a/web/handlers.go +++ b/web/handlers.go @@ -92,6 +92,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.App = app.New( h.GetGlobalAppOptions()..., ) + c.App.InitServer() t, _ := utils.GetTranslationsAndLocale(w, r) c.App.SetT(t) @@ -143,7 +144,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { c.SetSiteURLHeader(siteURLHeader) w.Header().Set(model.HEADER_REQUEST_ID, c.App.RequestId()) - w.Header().Set(model.HEADER_VERSION_ID, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.License() != nil)) + w.Header().Set(model.HEADER_VERSION_ID, fmt.Sprintf("%v.%v.%v.%v", model.CurrentVersion, model.BuildNumber, c.App.ClientConfigHash(), c.App.Srv().License() != nil)) if *c.App.Config().ServiceSettings.TLSStrictTransport { w.Header().Set("Strict-Transport-Security", fmt.Sprintf("max-age=%d", *c.App.Config().ServiceSettings.TLSStrictTransportMaxAge)) diff --git a/web/unsupported_browser.go b/web/unsupported_browser.go index 6c9debbfdc..695a2b2443 100644 --- a/web/unsupported_browser.go +++ b/web/unsupported_browser.go @@ -46,7 +46,7 @@ type SystemBrowser struct { func renderUnsupportedBrowser(app app.AppIface, w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") - page := utils.NewHTMLTemplate(app.HTMLTemplates(), "unsupported_browser") + page := utils.NewHTMLTemplate(app.Srv().HTMLTemplates(), "unsupported_browser") // User Agent info ua := uasurfer.Parse(r.UserAgent()) diff --git a/web/web_test.go b/web/web_test.go index a2f0046a5d..5c888bb5c7 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -85,17 +85,16 @@ func setupTestHelper(t testing.TB, store store.Store, includeCacheLayer bool) *T s.Store = localcachelayer.NewLocalCacheLayer(s.Store, s.Metrics, s.Cluster, s.CacheProvider) } - a := s.FakeApp() - prevListenAddress := *a.Config().ServiceSettings.ListenAddress - a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" }) + prevListenAddress := *s.Config().ServiceSettings.ListenAddress + s.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" }) serverErr := s.Start() if serverErr != nil { panic(serverErr) } - a.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) + s.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) // Disable strict password requirements for test - a.UpdateConfig(func(cfg *model.Config) { + s.UpdateConfig(func(cfg *model.Config) { *cfg.PasswordSettings.MinimumLength = 5 *cfg.PasswordSettings.Lowercase = false *cfg.PasswordSettings.Uppercase = false @@ -103,15 +102,16 @@ func setupTestHelper(t testing.TB, store store.Store, includeCacheLayer bool) *T *cfg.PasswordSettings.Number = false }) + a := app.New(app.ServerConnector(s)) + a.InitServer() + web := New(s, s.AppOptions, s.Router) - URL = fmt.Sprintf("http://localhost:%v", a.Srv().ListenAddr.Port) + URL = fmt.Sprintf("http://localhost:%v", s.ListenAddr.Port) ApiClient = model.NewAPIv4Client(URL) - a.DoAppMigrations() + s.Store.MarkSystemRanUnitTests() - a.Srv().Store.MarkSystemRanUnitTests() - - a.UpdateConfig(func(cfg *model.Config) { + s.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) @@ -155,7 +155,7 @@ func (th *TestHelper) InitBasic() *TestHelper { func (th *TestHelper) TearDown() { if th.IncludeCacheLayer { // Clean all the caches - th.App.InvalidateAllCaches() + th.App.Srv().InvalidateAllCaches() } th.Server.Shutdown() } diff --git a/web/webhook_test.go b/web/webhook_test.go index 722e8991f8..c8aed89a5a 100644 --- a/web/webhook_test.go +++ b/web/webhook_test.go @@ -130,7 +130,7 @@ func TestIncomingWebhook(t *testing.T) { }) t.Run("WebhookExperimentalReadOnly", func(t *testing.T) { - th.App.SetLicense(model.NewTestLicense()) + th.App.Srv().SetLicense(model.NewTestLicense()) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true }) // Read only default channel should fail. diff --git a/wsapi/api.go b/wsapi/api.go index de430bcda3..1c601c5c70 100644 --- a/wsapi/api.go +++ b/wsapi/api.go @@ -12,10 +12,11 @@ type API struct { Router *app.WebSocketRouter } -func Init(a *app.App, router *app.WebSocketRouter) { +func Init(s *app.Server) { + a := app.New(app.ServerConnector(s)) api := &API{ App: a, - Router: router, + Router: s.WebSocketRouter, } api.InitUser()