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

chore: makes instance-status works along with Moleculer lifecyle #34134

Merged
merged 16 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
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
83 changes: 26 additions & 57 deletions apps/meteor/ee/server/local-services/instance/service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os from 'os';

import { License, ServiceClassInternal } from '@rocket.chat/core-services';
import { InstanceStatus } from '@rocket.chat/instance-status';
import { InstanceStatus, defaultPingInterval, indexExpire } from '@rocket.chat/instance-status';
import { InstanceStatus as InstanceStatusRaw } from '@rocket.chat/models';
import EJSON from 'ejson';
import type { BrokerNode } from 'moleculer';
Expand Down Expand Up @@ -42,27 +42,32 @@ export class InstanceService extends ServiceClassInternal implements IInstanceSe
constructor() {
super();

const tx = getTransporter({ transporter: process.env.TRANSPORTER, port: process.env.TCP_PORT, extra: process.env.TRANSPORTER_EXTRA });
if (typeof tx === 'string') {
this.transporter = new Transporters.NATS({ url: tx });
this.isTransporterTCP = false;
} else {
this.transporter = new Transporters.TCP(tx);
}
const transporter = getTransporter({
transporter: process.env.TRANSPORTER,
port: process.env.TCP_PORT,
extra: process.env.TRANSPORTER_EXTRA,
});
this.isTransporterTCP = typeof transporter !== 'string';

if (this.isTransporterTCP) {
this.onEvent('watch.instanceStatus', async ({ clientAction, data }): Promise<void> => {
if (clientAction === 'removed') {
(this.broker.transit?.tx as any).nodes.disconnected(data?._id, false);
(this.broker.transit?.tx as any).nodes.nodes.delete(data?._id);
return;
}

if (clientAction === 'inserted' && data?.extraInformation?.tcpPort) {
this.connectNode(data);
}
});
}
const activeInstances = InstanceStatusRaw.getActiveInstancesAddress()
.then((instances) => {
console.info(`Found ${instances.length} active instances`);
return instances;
})
.catch(() => []);

this.transporter = this.isTransporterTCP
? new Transporters.TCP({ ...transporter, urls: activeInstances })
: new Transporters.NATS({ url: transporter });

this.broker = new ServiceBroker({
nodeID: InstanceStatus.id(),
transporter: this.transporter,
serializer: new EJSONSerializer(),
heartbeatInterval: defaultPingInterval,
heartbeatTimeout: indexExpire,
...getLogger(process.env),
});

this.onEvent('license.module', async ({ module, valid }) => {
if (module === 'scalability' && valid) {
Expand Down Expand Up @@ -93,17 +98,6 @@ export class InstanceService extends ServiceClassInternal implements IInstanceSe
}

async created() {
this.broker = new ServiceBroker({
nodeID: InstanceStatus.id(),
transporter: this.transporter,
serializer: new EJSONSerializer(),
...getLogger(process.env),
});

if ((this.broker.transit?.tx as any)?.nodes?.localNode) {
(this.broker.transit?.tx as any).nodes.localNode.ipList = [hostIP];
}

this.broker.createService({
name: 'matrix',
events: {
Expand Down Expand Up @@ -176,31 +170,6 @@ export class InstanceService extends ServiceClassInternal implements IInstanceSe
this.broadcastStarted = true;

StreamerCentral.on('broadcast', this.sendBroadcast.bind(this));

if (this.isTransporterTCP) {
await InstanceStatusRaw.find(
{
'extraInformation.tcpPort': {
$exists: true,
},
},
{
sort: {
_createdAt: -1,
},
},
).forEach(this.connectNode.bind(this));
}
}

private connectNode(record: any) {
if (record._id === InstanceStatus.id()) {
return;
}

const { host, tcpPort } = record.extraInformation;

(this.broker?.transit?.tx as any).addOfflineNode(record._id, host, tcpPort);
}

private sendBroadcast(streamName: string, eventName: string, args: unknown[]) {
Expand Down
3 changes: 2 additions & 1 deletion apps/meteor/server/database/watchCollections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@ const onlyCollections = DBWATCHER_ONLY_COLLECTIONS.split(',')
.filter(Boolean);

export function getWatchCollections(): string[] {
const collections = [InstanceStatus.getCollectionName()];
const collections = [];

// add back to the list of collections in case db watchers are enabled
if (!dbWatchersDisabled) {
collections.push(InstanceStatus.getCollectionName());
collections.push(Users.getCollectionName());
collections.push(Messages.getCollectionName());
collections.push(LivechatInquiry.getCollectionName());
Expand Down
11 changes: 10 additions & 1 deletion apps/meteor/server/models/raw/InstanceStatus.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { IInstanceStatus } from '@rocket.chat/core-typings';
import type { IInstanceStatusModel } from '@rocket.chat/model-typings';
import type { Db } from 'mongodb';
import type { Db, UpdateResult } from 'mongodb';

import { BaseRaw } from './BaseRaw';

Expand All @@ -17,4 +17,13 @@ export class InstanceStatusRaw extends BaseRaw<IInstanceStatus> implements IInst
async getActiveInstanceCount(): Promise<number> {
return this.col.countDocuments({ _updatedAt: { $gt: new Date(Date.now() - process.uptime() * 1000 - 2000) } });
}

async getActiveInstancesAddress(): Promise<string[]> {
const instances = await this.find({}, { projection: { _id: 1, extraInformation: { host: 1, tcpPort: 1 } } }).toArray();
return instances.map((instance) => `${instance.extraInformation.host}:${instance.extraInformation.tcpPort}/${instance._id}`);
}

async setDocumentHeartbeat(documentId: string): Promise<UpdateResult> {
return this.updateOne({ _id: documentId }, { $currentDate: { _updatedAt: true } });
}
}
17 changes: 11 additions & 6 deletions apps/meteor/server/startup/watchDb.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { api } from '@rocket.chat/core-services';
import { api, dbWatchersDisabled } from '@rocket.chat/core-services';
import { Logger } from '@rocket.chat/logger';
import { MongoInternals } from 'meteor/mongo';

Expand All @@ -19,12 +19,17 @@ watcher.watch().catch((err: Error) => {
process.exit(1);
});

setInterval(function _checkDatabaseWatcher() {
if (watcher.isLastDocDelayed()) {
SystemLogger.error('No real time data received recently');
}
}, 20000);
if (!dbWatchersDisabled) {
setInterval(function _checkDatabaseWatcher() {
if (watcher.isLastDocDelayed()) {
SystemLogger.error('No real time data received recently');
}
}, 20000);
}

export function isLastDocDelayed(): boolean {
if (dbWatchersDisabled) {
return true;
}
return watcher.isLastDocDelayed();
}
Loading
Loading