Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New: Use database change streams when available #18892

Merged
merged 26 commits into from
Sep 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
373d0d7
Remove unused file roomFiles.js
rodrigok Sep 13, 2020
30084e2
Prevent uncessary listeners to the oplog changes
rodrigok Sep 13, 2020
bb5ed91
Remove missing observers on settings
rodrigok Sep 13, 2020
5949a8b
Remove observer from integrations
rodrigok Sep 13, 2020
207dbd3
Remove settings observers for cache
rodrigok Sep 13, 2020
522c2e7
Remove observer from instance status
rodrigok Sep 13, 2020
9788908
Remove observer from presence monitoring
rodrigok Sep 13, 2020
46706ae
Very first concept of changestream in place of oplog
rodrigok Sep 13, 2020
a269a23
Reduce observers to prevent unecessary finds
rodrigok Sep 13, 2020
cdcdcc6
Handle oplog options
rodrigok Sep 13, 2020
5bb310a
Fix url parse
rodrigok Sep 13, 2020
58d9caf
Fix importer issue
rodrigok Sep 14, 2020
553a9d7
Verify if mongodb is gte 3.6 to allow usage of changestreams
rodrigok Sep 14, 2020
3238a94
Update settings cache after change via API
rodrigok Sep 14, 2020
73ace9f
Add settings emitter
sampaiodiego Sep 14, 2020
f3fc83b
Prevent polling of users’ tokens due to logout reactivity
rodrigok Sep 15, 2020
e1b0cfc
Merge branch 'develop' into change-streams
sampaiodiego Sep 17, 2020
e17189b
Remove package to disable oplog and use env USE_NATIVE_OPLOG to contr…
rodrigok Sep 18, 2020
d9bfd54
Merge branch 'develop' into change-streams
rodrigok Sep 18, 2020
f05c92e
Merge remote-tracking branch 'origin/develop' into change-streams
rodrigok Sep 21, 2020
345e54d
Fix review
rodrigok Sep 21, 2020
8b7c962
Merge remote-tracking branch 'origin/develop' into change-streams
rodrigok Sep 21, 2020
51eca3b
Merge branch 'develop' into change-streams
sampaiodiego Sep 22, 2020
0f91ff4
Improve error handling
rodrigok Sep 22, 2020
af2e821
Merge branch 'change-streams' of github.com:RocketChat/Rocket.Chat in…
sampaiodiego Sep 22, 2020
24a392a
Code cleanup
sampaiodiego Sep 22, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion app/api/server/v1/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import _ from 'underscore';
import { Settings } from '../../../models/server';
import { hasPermission } from '../../../authorization';
import { API } from '../api';
import { SettingsEvents } from '../../../settings/server';
import { SettingsEvents, settings } from '../../../settings/server';

const fetchSettings = (query, sort, offset, count, fields) => {
const settings = Settings.find(query, {
Expand Down Expand Up @@ -146,6 +146,10 @@ API.v1.addRoute('settings/:_id', { authRequired: true }, {
value: Match.Any,
});
if (Settings.updateValueNotHiddenById(this.urlParams._id, this.bodyParams.value)) {
settings.storeSettingValue({
_id: this.urlParams._id,
value: this.bodyParams.value,
});
return API.v1.success();
}

Expand Down
17 changes: 2 additions & 15 deletions app/assets/server/assets.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import _ from 'underscore';
import sizeOf from 'image-size';
import sharp from 'sharp';

import { settings } from '../../settings';
import { Settings } from '../../models';
import { settings } from '../../settings/server';
import { getURL } from '../../utils/lib/getURL';
import { mime } from '../../utils/lib/mimeTypes';
import { hasPermission } from '../../authorization';
Expand Down Expand Up @@ -354,19 +353,7 @@ for (const key of Object.keys(assets)) {
addAssetToSetting(key, value);
}

Settings.find().observe({
added(record) {
return RocketChatAssets.processAsset(record._id, record.value);
},

changed(record) {
return RocketChatAssets.processAsset(record._id, record.value);
},

removed(record) {
return RocketChatAssets.processAsset(record._id, undefined);
},
});
settings.get(/^Assets_/, (key, value) => RocketChatAssets.processAsset(key, value));

Meteor.startup(function() {
return Meteor.setTimeout(function() {
Expand Down
2 changes: 1 addition & 1 deletion app/authorization/server/streamer/permissions/emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Permissions.on('change', ({ clientAction, id, data, diff }) => {
switch (clientAction) {
case 'updated':
case 'inserted':
data = data || Permissions.findOneById(id);
data = data ?? Permissions.findOneById(id);
break;

case 'removed':
Expand Down
13 changes: 3 additions & 10 deletions app/dolphin/lib/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { ServiceConfiguration } from 'meteor/service-configuration';
import { settings } from '../../settings';
import { CustomOAuth } from '../../custom-oauth';
import { callbacks } from '../../callbacks';
import { Settings } from '../../models';

const config = {
serverURL: '',
Expand All @@ -31,15 +30,9 @@ function DolphinOnCreateUser(options, user) {

if (Meteor.isServer) {
Meteor.startup(() =>
Settings.find({ _id: 'Accounts_OAuth_Dolphin_URL' }).observe({
added() {
config.serverURL = settings.get('Accounts_OAuth_Dolphin_URL');
return Dolphin.configure(config);
},
changed() {
config.serverURL = settings.get('Accounts_OAuth_Dolphin_URL');
return Dolphin.configure(config);
},
settings.get('Accounts_OAuth_Dolphin_URL', (key, value) => {
config.serverURL = value;
return Dolphin.configure(config);
}),
);

Expand Down
31 changes: 19 additions & 12 deletions app/integrations/server/lib/triggerHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,26 @@ integrations.triggerHandler = new class RocketChatIntegrationHandler {
this.compiledScripts = {};
this.triggers = {};

Models.Integrations.find({ type: 'webhook-outgoing' }).observe({
added: (record) => {
this.addIntegration(record);
},

changed: (record) => {
this.removeIntegration(record);
this.addIntegration(record);
},
Models.Integrations.find({ type: 'webhook-outgoing' }).fetch().forEach((data) => this.addIntegration(data));

removed: (record) => {
this.removeIntegration(record);
},
Models.Integrations.on('change', ({ clientAction, id, data }) => {
switch (clientAction) {
case 'inserted':
if (data.type === 'webhook-outgoing') {
this.addIntegration(data);
}
break;
case 'updated':
data = data ?? Models.Integrations.findOneById(id);
if (data.type === 'webhook-outgoing') {
this.removeIntegration(data);
this.addIntegration(data);
}
break;
case 'removed':
this.removeIntegration({ _id: id });
break;
}
});
}

Expand Down
63 changes: 63 additions & 0 deletions app/lib/server/startup/userDataStream.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,73 @@
import { MongoInternals } from 'meteor/mongo';

import { Users } from '../../../models/server';
import { Notifications } from '../../../notifications/server';

let processOnChange;
// eslint-disable-next-line no-undef
const disableOplog = Package['disable-oplog'];

if (disableOplog) {
// Stores the callbacks for the disconnection reactivity bellow
const userCallbacks = new Map();

// Overrides the native observe changes to prevent database polling and stores the callbacks
// for the users' tokens to re-implement the reactivity based on our database listeners
const { mongo } = MongoInternals.defaultRemoteCollectionDriver();
MongoInternals.Connection.prototype._observeChanges = function({ collectionName, selector, options = {} }, _ordered, callbacks) {
// console.error('Connection.Collection.prototype._observeChanges', collectionName, selector, options);
let cbs;
if (callbacks?.added) {
const records = Promise.await(mongo.rawCollection(collectionName).find(selector, { projection: options.fields }).toArray());
for (const { _id, ...fields } of records) {
callbacks.added(_id, fields);
}

if (collectionName === 'users' && selector['services.resume.loginTokens.hashedToken']) {
cbs = userCallbacks.get(selector._id) || new Set();
cbs.add({
hashedToken: selector['services.resume.loginTokens.hashedToken'],
callbacks,
});
userCallbacks.set(selector._id, cbs);
}
}
return {
stop() {
if (cbs) {
cbs.delete(callbacks);
}
},
};
};

// Re-implement meteor's reactivity that uses observe to disconnect sessions when the token
// associated was removed
processOnChange = (diff, id) => {
const loginTokens = diff['services.resume.loginTokens'];
if (loginTokens) {
const tokens = loginTokens.map(({ hashedToken }) => hashedToken);

const cbs = userCallbacks.get(id);
if (cbs) {
[...cbs].filter(({ hashedToken }) => !tokens.includes(hashedToken)).forEach((item) => {
item.callbacks.removed(id);
cbs.delete(item);
});
}
}
};
}

Users.on('change', ({ clientAction, id, data, diff }) => {
switch (clientAction) {
case 'updated':
Notifications.notifyUserInThisInstance(id, 'userData', { diff, type: clientAction });

if (disableOplog) {
processOnChange(diff, id);
}

break;
case 'inserted':
Notifications.notifyUserInThisInstance(id, 'userData', { data, type: clientAction });
Expand Down
1 change: 1 addition & 0 deletions app/metrics/server/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { metrics } from './lib/metrics';
import StatsTracker from './lib/statsTracker';

import './lib/collectMetrics';
import './callbacksMetrics';

export {
Expand Down
177 changes: 177 additions & 0 deletions app/metrics/server/lib/collectMetrics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import http from 'http';

import client from 'prom-client';
import connect from 'connect';
import _ from 'underscore';
import gcStats from 'prometheus-gc-stats';
import { Meteor } from 'meteor/meteor';
import { Facts } from 'meteor/facts-base';

import { Info, getOplogInfo } from '../../../utils/server';
import { Migrations } from '../../../migrations';
import { settings } from '../../../settings';
import { Statistics } from '../../../models';
import { metrics } from './metrics';

Facts.incrementServerFact = function(pkg, fact, increment) {
metrics.meteorFacts.inc({ pkg, fact }, increment);
};

const setPrometheusData = async () => {
metrics.info.set({
version: Info.version,
unique_id: settings.get('uniqueID'),
site_url: settings.get('Site_Url'),
}, 1);

const sessions = Array.from(Meteor.server.sessions.values());
const authenticatedSessions = sessions.filter((s) => s.userId);
metrics.ddpSessions.set(Meteor.server.sessions.size);
metrics.ddpAuthenticatedSessions.set(authenticatedSessions.length);
metrics.ddpConnectedUsers.set(_.unique(authenticatedSessions.map((s) => s.userId)).length);

const statistics = Statistics.findLast();
if (!statistics) {
return;
}

metrics.version.set({ version: statistics.version }, 1);
metrics.migration.set(Migrations._getControl().version);
metrics.instanceCount.set(statistics.instanceCount);
metrics.oplogEnabled.set({ enabled: statistics.oplogEnabled }, 1);

// User statistics
metrics.totalUsers.set(statistics.totalUsers);
metrics.activeUsers.set(statistics.activeUsers);
metrics.nonActiveUsers.set(statistics.nonActiveUsers);
metrics.onlineUsers.set(statistics.onlineUsers);
metrics.awayUsers.set(statistics.awayUsers);
metrics.offlineUsers.set(statistics.offlineUsers);

// Room statistics
metrics.totalRooms.set(statistics.totalRooms);
metrics.totalChannels.set(statistics.totalChannels);
metrics.totalPrivateGroups.set(statistics.totalPrivateGroups);
metrics.totalDirect.set(statistics.totalDirect);
metrics.totalLivechat.set(statistics.totalLivechat);

// Message statistics
metrics.totalMessages.set(statistics.totalMessages);
metrics.totalChannelMessages.set(statistics.totalChannelMessages);
metrics.totalPrivateGroupMessages.set(statistics.totalPrivateGroupMessages);
metrics.totalDirectMessages.set(statistics.totalDirectMessages);
metrics.totalLivechatMessages.set(statistics.totalLivechatMessages);

const oplogQueue = getOplogInfo().mongo._oplogHandle?._entryQueue?.length || 0;
metrics.oplogQueue.set(oplogQueue);

metrics.pushQueue.set(statistics.pushQueue || 0);
};

const app = connect();

// const compression = require('compression');
// app.use(compression());

app.use('/metrics', (req, res) => {
res.setHeader('Content-Type', 'text/plain');
const data = client.register.metrics();

metrics.metricsRequests.inc();
metrics.metricsSize.set(data.length);

res.end(data);
});

app.use('/', (req, res) => {
const html = `<html>
<head>
<title>Rocket.Chat Prometheus Exporter</title>
</head>
<body>
<h1>Rocket.Chat Prometheus Exporter</h1>
<p><a href="/metrics">Metrics</a></p>
</body>
</html>`;

res.write(html);
res.end();
});

const server = http.createServer(app);

let timer;
let resetTimer;
let defaultMetricsInitiated = false;
let gcStatsInitiated = false;
const was = {
enabled: false,
port: 9458,
resetInterval: 0,
collectGC: false,
};
const updatePrometheusConfig = async () => {
const is = {
port: process.env.PROMETHEUS_PORT || settings.get('Prometheus_Port'),
enabled: settings.get('Prometheus_Enabled'),
resetInterval: settings.get('Prometheus_Reset_Interval'),
collectGC: settings.get('Prometheus_Garbage_Collector'),
};

if (Object.values(is).some((s) => s == null)) {
return;
}

if (Object.entries(is).every(([k, v]) => v === was[k])) {
return;
}

if (!is.enabled) {
if (was.enabled) {
console.log('Disabling Prometheus');
server.close();
Meteor.clearInterval(timer);
}
Object.assign(was, is);
return;
}

console.log('Configuring Prometheus', is);

if (!was.enabled) {
server.listen({
port: is.port,
host: process.env.BIND_IP || '0.0.0.0',
});

timer = Meteor.setInterval(setPrometheusData, 5000);
}

Meteor.clearInterval(resetTimer);
if (is.resetInterval) {
resetTimer = Meteor.setInterval(() => {
client.register.getMetricsAsArray().forEach((metric) => { metric.hashMap = {}; });
}, is.resetInterval);
}

// Prevent exceptions on calling those methods twice since
// it's not possible to stop them to be able to restart
try {
if (defaultMetricsInitiated === false) {
defaultMetricsInitiated = true;
client.collectDefaultMetrics();
}
if (is.collectGC && gcStatsInitiated === false) {
gcStatsInitiated = true;
gcStats()();
}
} catch (error) {
console.error(error);
}

Object.assign(was, is);
};

Meteor.startup(async () => {
settings.get(/^Prometheus_.+/, updatePrometheusConfig);
});
Loading