ยง2024-06-02

  1. server_ys20220318.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const { MongoClient } = require('mongodb');

const uri = "ongodb+srv://siteRootAdmin:b23258585@ys20220318.yushei.com.tw/syslog_ng_db?replicaSet=ys20220318&authSource=admin&tls=false")
      collection("ys20220318Replication";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

const port = process.env.PORT || 48599

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index_ys20220318.html');
});

async function run() {
    try {
        await client.connect();
        console.log("Connected to the database!");

        const db = client.db('syslog_ng_db');
        const collection = db.collection('Odroid01Replication');

        console.log("Watching for insertions in the 'Odroid01Replication' collection...");

        // Open a change stream on the collection with a filter for insert operations
        const changeStream = collection.watch(
            [{ $match: { 'operationType': 'insert' } }],
            { fullDocument: 'updateLookup' }
        );

        // Listen for changes in the stream
        changeStream.on('change', (change) => {
            if (change.fullDocument) {
                const doc = change.fullDocument;
                const message = JSON.stringify(doc).toLowerCase();

                if (message.includes('replication') || message.includes('error') || message.includes('slow') || message.includes('ReplicaSetMonitor-TaskExecutor') ) {
                    console.log('Relevant event detected:');
                    console.log(doc);
                    io.emit('newDocument', doc);
                }
            }
        });
    } catch (err) {
        console.error(err);
    }
}

run().catch(console.dir);

server.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});