index.js 21.4 KB
Newer Older
nilanjandaw's avatar
nilanjandaw committed
1
"use strict";
2

3
const express = require('express');
nilanjandaw's avatar
nilanjandaw committed
4
const fileUpload = require('express-fileupload');
5 6 7 8
const constants = require('.././constants.json');
const chainHandler = require('./explicit_chain_handler');
const secrets = require('./secrets.json');
const fs = require('fs');
nilanjandaw's avatar
nilanjandaw committed
9
const { spawn } = require('child_process');
10 11
const morgan = require('morgan');
const heap = require('heap');
12
const fetch = require('node-fetch');
Nilanjan Daw's avatar
Nilanjan Daw committed
13 14
const swStats = require('swagger-stats');
const apiSpec = require('./swagger.json');
15
const util = require('util')
16
const sharedStructures = require('./shared_structures')
17

18 19 20
/**
 * URL to the couchdb database server used to store function metadata
 */
21
let metadataDB = `http://${secrets.couchdb_username}:${secrets.couchdb_password}@${constants.couchdb_host}`
Nilanjan Daw's avatar
Nilanjan Daw committed
22
metadataDB = metadataDB + "/" + constants.function_db_name + "/"
Nilanjan Daw's avatar
Nilanjan Daw committed
23

24 25 26
let metricsDB = `http://${secrets.couchdb_username}:${secrets.couchdb_password}@${constants.couchdb_host}`
metricsDB = metricsDB + "/" + constants.metrics_db_name + "/"

nilanjandaw's avatar
nilanjandaw committed
27
const app = express()
28
const libSupport = require('./lib')
Nilanjan Daw's avatar
Nilanjan Daw committed
29
const logger = libSupport.logger
Nilanjan Daw's avatar
Nilanjan Daw committed
30
let date = new Date();
31
let log_channel = constants.topics.log_channel
Nilanjan Daw's avatar
Nilanjan Daw committed
32

33
let usedPort = new Map(), // TODO: remove after integration with RM
34 35 36
    db = sharedStructures.db, // queue holding request to be dispatched
    resourceMap = sharedStructures.resourceMap, // map between resource_id and resource details like node_id, port, associated function etc
    functionToResource = sharedStructures.functionToResource, // a function to resource map. Each map contains a minheap of
37
                                   // resources associated with the function
38 39
    workerNodes = sharedStructures.workerNodes, // list of worker nodes currently known to the DM
    functionBranchTree = sharedStructures.functionBranchTree // a tree to store function branch predictions
Nilanjan Daw's avatar
Nilanjan Daw committed
40
    
41
chainHandler.initialise(functionToResource)
42 43 44
let kafka = require('kafka-node'),
    Producer = kafka.Producer,
    client = new kafka.KafkaClient({ 
45
        kafkaHost: constants.network.external.kafka_host,
46 47 48 49 50 51
        autoConnect: true
    }),
    producer = new Producer(client),
    Consumer = kafka.Consumer,
    consumer = new Consumer(client,
        [
52 53 54 55 56
            { topic: constants.topics.heartbeat }, // receives heartbeat messages from workers, also acts as worker join message
            { topic: constants.topics.deployed }, // receives deployment confirmation from workers
            { topic: constants.topics.remove_worker }, // received when a executor environment is blown at the worker
            { topic: constants.topics.response_rm_2_dm }, // receives deployment details from RM
            { topic: constants.topics.hscale } // receives signals for horizontal scaling
57 58
        ],
        [
59
            { autoCommit: true }
60 61
        ])

Nilanjan Daw's avatar
Nilanjan Daw committed
62 63 64
app.use(morgan('combined', {
    skip: function (req, res) { return res.statusCode < 400 }
}))
65 66
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
67
const file_path = __dirname + "/repository/"
68
app.use('/repository', express.static(file_path)); // file server hosting deployed functions
nilanjandaw's avatar
nilanjandaw committed
69
app.use(fileUpload())
70
app.use(swStats.getMiddleware({ swaggerSpec: apiSpec })); // statistics middleware
71
app.use('/serverless/chain', chainHandler.router); // chain router (explicit_chain_handler.js) for handling explicit chains
72 73
let requestQueue = []

74
const WINDOW_SIZE = 10
nilanjandaw's avatar
nilanjandaw committed
75
const port = constants.master_port
nilanjandaw's avatar
nilanjandaw committed
76
const registry_url = constants.registry_url
77

78 79 80 81 82
app.get('/metrics', (req, res) => {
    res.set('Content-Type', libSupport.metrics.register.contentType);
    res.end(libSupport.metrics.register.metrics());
});

Nilanjan Daw's avatar
Nilanjan Daw committed
83 84 85
/**
 * REST API to receive deployment requests
 */
nilanjandaw's avatar
nilanjandaw committed
86 87 88 89 90 91
app.post('/serverless/deploy', (req, res) => {
    
    let runtime = req.body.runtime
    let file = req.files.serverless

    let functionHash = file.md5
92

93
    file.mv(file_path + functionHash, function (err) { // move function file to repository
94
        functionHash = libSupport.generateExecutor(file_path, functionHash)
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
        /**
         * Adding meta caching via couchdb
         * This will create / update function related metadata like resource limits etc
         * on a database named "serverless".
         */
        fetch(metadataDB + functionHash).then(res => res.json())
            .then(json => {
                if (json.error === "not_found") {
                    logger.warn("New function, creating metadata")
                    fetch(metadataDB + functionHash, {
                        method: 'put',
                        body: JSON.stringify({
                            memory: req.body.memory
                        }),
                        headers: { 'Content-Type': 'application/json' },
                    }).then(res => res.json())
                    .then(json => console.log(json));
                } else {
                    logger.warn('Repeat deployment, updating metadata')
                    fetch(metadataDB + functionHash, {
                        method: 'put',
                        body: JSON.stringify({
                            memory: req.body.memory,
                            _rev: json._rev
                        }),
                        headers: { 'Content-Type': 'application/json' },
                    }).then(res => res.json())
                    .then(json => console.log(json));
                }
        });
nilanjandaw's avatar
nilanjandaw committed
125
        if (err) {
Nilanjan Daw's avatar
Nilanjan Daw committed
126
            logger.error(err)
nilanjandaw's avatar
nilanjandaw committed
127 128 129 130
            res.send("error").status(400)
        }
        else {
            if (runtime === "container") {
131
                deployContainer(file_path, functionHash)
nilanjandaw's avatar
nilanjandaw committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
                    .then(() => {
                        res.json({
                            status: "success",
                            function_id: functionHash
                        })
                    })
                    .catch(err => {
                        res.json({
                            status: "error",
                            reason: err}).status(400)
                    })
            } else {
                res.json({
                    status: "success",
                    function_id: functionHash
                })
            }
        }
    })
    
})

Nilanjan Daw's avatar
Nilanjan Daw committed
154 155 156 157 158
/**
 * Create the docker file, build and push image to remote repository
 * @param {String: Path from where to extract function executor} path 
 * @param {String: Name of the image} imageName 
 */
nilanjandaw's avatar
nilanjandaw committed
159 160 161
function deployContainer(path, imageName) {
    return new Promise((resolve, reject) => {
        let buildStart = Date.now()
162 163 164
        /**
         * Generating dockerfile for the received function
         */
nilanjandaw's avatar
nilanjandaw committed
165
        fs.writeFile('./repository/Dockerfile',
nilanjandaw's avatar
nilanjandaw committed
166 167
            `FROM node:latest
            WORKDIR /app
168 169 170
            COPY ./worker_env/package.json /app
            ADD ./worker_env/node_modules /app/node_modules
            COPY ${imageName}.js /app
171
            ENTRYPOINT ["node", "${imageName}.js"]`
nilanjandaw's avatar
nilanjandaw committed
172
            , function (err) {
173
                if (err) {
Nilanjan Daw's avatar
Nilanjan Daw committed
174 175
                    logger.error("failed", err);

176 177 178
                    
                    reject(err);
                }
nilanjandaw's avatar
nilanjandaw committed
179
                else {
Nilanjan Daw's avatar
Nilanjan Daw committed
180
                    logger.info('Dockerfile created');
181
                    const process = spawn('docker', ["build", "-t", registry_url + imageName, path]); // docker build
182

nilanjandaw's avatar
nilanjandaw committed
183
                    process.stdout.on('data', (data) => {
Nilanjan Daw's avatar
Nilanjan Daw committed
184
                        logger.info(`stdout: ${data}`);
nilanjandaw's avatar
nilanjandaw committed
185 186 187 188

                    });

                    process.stderr.on('data', (data) => {
Nilanjan Daw's avatar
Nilanjan Daw committed
189
                        logger.error(`stderr: ${data}`);
nilanjandaw's avatar
nilanjandaw committed
190
                    });
191

nilanjandaw's avatar
nilanjandaw committed
192
                    process.on('close', (code) => {
Nilanjan Daw's avatar
Nilanjan Daw committed
193
                        logger.warn(`child process exited with code ${code}`);
nilanjandaw's avatar
nilanjandaw committed
194
                        let timeDifference = Math.ceil((Date.now() - buildStart))
Nilanjan Daw's avatar
Nilanjan Daw committed
195
                        logger.info("image build time taken: ", timeDifference);
196
                        const process_push = spawn('docker', ["push", registry_url + imageName]); // docker push image to local registry
197 198 199 200 201 202 203

                        process_push.stdout.on('data', (data) => {
                            console.log(`stdout: ${data}`);

                        });

                        process_push.stderr.on('data', (data) => {
Nilanjan Daw's avatar
Nilanjan Daw committed
204
                            logger.error(`stderr: ${data}`);
205 206 207
                        });

                        process_push.on('close', (code) => {
Nilanjan Daw's avatar
Nilanjan Daw committed
208
                            logger.info("image pushed to repository");
209 210 211
                            resolve();
                        })
                        
nilanjandaw's avatar
nilanjandaw committed
212 213
                    });
                }
214
            });
nilanjandaw's avatar
nilanjandaw committed
215 216 217
    })
}

Nilanjan Daw's avatar
Nilanjan Daw committed
218 219 220
/**
 * REST API to receive execute requests
 */
221
app.post('/serverless/execute/:id', (req, res) => {
222

nilanjandaw's avatar
nilanjandaw committed
223
    let runtime = req.body.runtime
224
    let id = req.params.id + runtime
225
    res.timestamp = Date.now() 
226
    if (functionToResource.has(id)) {
Nilanjan Daw's avatar
Nilanjan Daw committed
227
        res.start = 'warmstart'
228
        libSupport.reverseProxy(req, res, functionToResource, resourceMap, functionBranchTree)
nilanjandaw's avatar
nilanjandaw committed
229
    } else {
Nilanjan Daw's avatar
Nilanjan Daw committed
230
        res.start = 'coldstart'
231
        /**
232 233 234
         * Requests are queued up before being dispatched. To prevent requests coming in for the 
         * same function from starting too many workers, they are grouped together
         * and one worker is started per group.
235
         */
236 237 238 239
        if (db.has(req.params.id + runtime)) {
            db.get(req.params.id + runtime).push({ req, res })
            return;
        }
nilanjandaw's avatar
nilanjandaw committed
240
        requestQueue.push({ req, res })
Nilanjan Daw's avatar
Nilanjan Daw committed
241 242 243 244
        /**
         * We store functions for function placement heuristics purposes. This lets us look into the function
         * patterns being received and make intelligent deployment decisions based on it.
         */
nilanjandaw's avatar
nilanjandaw committed
245 246 247
        if (requestQueue.length >= WINDOW_SIZE)
            dispatch()
    }
248
})
nilanjandaw's avatar
nilanjandaw committed
249

Nilanjan Daw's avatar
Nilanjan Daw committed
250
/**
251
 * Send dispatch signal to Worker nodes and deploy resources after consultation with the RM
Nilanjan Daw's avatar
Nilanjan Daw committed
252
 */
253
function dispatch() {
254 255 256 257
    /**
     * The lookahead window will be used for optimisation purposes
     * Ex. It might be used to co-group similar runtimes on same machines
     */
258 259
    let lookbackWindow = Math.min(WINDOW_SIZE, requestQueue.length)
    for (let i = 0; i < lookbackWindow; i++) {
260
        let {req, res} = requestQueue.shift()
261
        
262
	    // logger.info(req.body)
263 264
        let runtime = req.body.runtime
        let functionHash = req.params.id
265 266
        if (!db.has(functionHash + runtime)) {
            db.set(functionHash + runtime, [])
267
            db.get(functionHash + runtime).push({ req, res })
268
            
269 270 271
            let payload = [{
                topic: constants.topics.hscale,
                messages: JSON.stringify({ runtime, functionHash })
Nilanjan Daw's avatar
Nilanjan Daw committed
272
            }]
273
            producer.send(payload, function () { })
274

275
            speculative_deployment(req, runtime)
Nilanjan Daw's avatar
Nilanjan Daw committed
276 277 278 279 280
        } else {
            logger.info("deployment process already started waiting")
            db.get(functionHash + runtime).push({ req, res })
        }

281 282 283 284
        
    }
}

285 286 287 288
/**
 * Handles post deployment metadata updates and starts reverse-proxying
 * @param {string} message Message received from DD after deployment
 */
289 290
function postDeploy(message) {
    logger.info("Deployed Resource: " + JSON.stringify(message));
291
    let id = message.functionHash + message.runtime
292
    if (message.status == false) {
293
        let sendQueue = db.get(id)
294 295 296 297 298
        // TODO: handle failure
        while (sendQueue && sendQueue.length != 0) {
            let { req, res } = sendQueue.shift()
            res.status(400).json({ reason: message.reason })
        }
299
        db.delete(id)
300 301 302
        
        return;
    }
303 304
    if (functionToResource.has(id)) {
        let resourceHeap = functionToResource.get(id)
305 306
        heap.push(resourceHeap, {
            resource_id: message.resource_id,
Nilanjan Daw's avatar
Nilanjan Daw committed
307
            open_request_count: 0
308 309
        }, libSupport.compare)
        logger.warn("Horizontally scaling up: " +
310
            JSON.stringify(functionToResource.get(id)));
311 312 313 314 315 316 317 318 319 320

    } else {
        /**
        * function to resource map - holds a min heap of resources associated with a function
        * the min heap is sorted based on a metric [TBD] like CPU usage, request count, mem usage etc
        * TODO: decide on metric to use for sorting.
        */
        let resourceHeap = []
        heap.push(resourceHeap, {
            resource_id: message.resource_id,
Nilanjan Daw's avatar
Nilanjan Daw committed
321
            open_request_count: 0
322
        }, libSupport.compare)
323
        functionToResource.set(id, resourceHeap)
324
        logger.warn("Creating new resource pool"
325
            + JSON.stringify(functionToResource.get(id)));
326 327

    }
328
    
Nilanjan Daw's avatar
Nilanjan Daw committed
329
    try {
330 331
        let resource = resourceMap.get(message.resource_id)
        resource.deployed = true
332 333 334 335
        libSupport.logBroadcast({
            entity_id: message.entity_id,
            "reason": "deployment",
            "status": true,
Nilanjan Daw's avatar
Nilanjan Daw committed
336
            starttime: (Date.now() - resource.deploy_request_time)
337
        }, message.resource_id, resourceMap)
338
        
339 340
        if (db.has(id)) {
            let sendQueue = db.get(id)
Nilanjan Daw's avatar
Nilanjan Daw committed
341 342 343
            logger.info("forwarding request via reverse proxy to: " + JSON.stringify(resource));
            while (sendQueue && sendQueue.length != 0) {
                let { req, res } = sendQueue.shift()
344
                libSupport.reverseProxy(req, res, functionToResource, resourceMap, functionBranchTree)
Nilanjan Daw's avatar
Nilanjan Daw committed
345
                    .then(() => {
346

Nilanjan Daw's avatar
Nilanjan Daw committed
347 348
                    })
            }
349
            db.delete(id)
350
        }
351 352
        
        libSupport.metrics.collectMetrics({type: "scale", value: 
353 354 355
            functionToResource.get(id).length, 
            functionHash: message.functionHash, runtime: message.runtime, 
            starttime: (Date.now() - resource.deploy_request_time)})
Nilanjan Daw's avatar
Nilanjan Daw committed
356 357
    } catch (e) {
        logger.error(e.message)
358 359 360 361
    }

}

362
consumer.on('message', function (message) {
Nilanjan Daw's avatar
Nilanjan Daw committed
363
    
364 365
    let topic = message.topic
        message = message.value
Nilanjan Daw's avatar
Nilanjan Daw committed
366
    // console.log(topic, message)
367
    if (topic === "response") {
368
        logger.info("response " + message);
Nilanjan Daw's avatar
Nilanjan Daw committed
369
        
Nilanjan Daw's avatar
Nilanjan Daw committed
370
        
371
    } else if (topic === constants.topics.heartbeat) {
372
        message = JSON.parse(message)
373
        if (Date.now() - message.timestamp < 1000)
374 375 376 377
            if (!workerNodes.has(message.address))  {
                workerNodes.set(message.address, message.timestamp)
                logger.warn("New worker discovered. Worker List: ")
                logger.warn(workerNodes)
Nilanjan Daw's avatar
Nilanjan Daw committed
378
            }
379
    } else if (topic == constants.topics.deployed) {
380 381 382 383 384
        try {
            message = JSON.parse(message)
        } catch (e) {
            // process.exit(0)
        }
385
        postDeploy(message)
nilanjandaw's avatar
nilanjandaw committed
386
        
387
    } else if (topic == constants.topics.remove_worker) {
388
        logger.warn("Worker blown: Removing Metadata " + message);
389 390 391 392 393
        try {
            message = JSON.parse(message)
        } catch(e) {
            // process.exit(0)
        }
nilanjandaw's avatar
nilanjandaw committed
394
        usedPort.delete(message.port)
395 396 397
        let id = message.functionHash + message.runtime
        if (functionToResource.has(id)) {
            let resourceArray = functionToResource.get(id)
398 399 400 401 402 403 404
            for (let i = 0; i < resourceArray.length; i++)
                if (resourceArray[i].resource_id === message.resource_id) {
                    resourceArray.splice(i, 1);
                    break;
                }

            heap.heapify(resourceArray, libSupport.compare)
405 406
            libSupport.metrics.collectMetrics({type: "scale", value: 
                resourceArray.length, 
Nilanjan Daw's avatar
Nilanjan Daw committed
407
                functionHash: message.functionHash, runtime: message.runtime})
408 409 410 411 412 413 414 415 416
            libSupport.logBroadcast({
                entity_id: message.entity_id,
                "reason": "terminate",
                "total_request": message.total_request,
                "status": true
            }, message.resource_id, resourceMap)
            .then(() => {
                resourceMap.delete(message.resource_id)
                if (resourceArray.length == 0)
417
                    functionToResource.delete(id)
418
            })
419 420
            
        }
421

422 423
        

424
    } else if (topic == constants.topics.hscale) {
425
        message = JSON.parse(message)
426
        let resource_id = libSupport.makeid(constants.id_size), // each function resource request is associated with an unique ID
427 428
            runtime = message.runtime,
            functionHash = message.functionHash
429
        logger.info(`Generated new resource ID: ${resource_id} for runtime: ${runtime}`);
Nilanjan Daw's avatar
Nilanjan Daw committed
430
        console.log("Resource Status: ", functionToResource);
431 432 433 434 435
        if (!functionToResource.has(functionHash + runtime) && !db.has(functionHash + runtime)) {
            console.log("adding db");
            
            db.set(functionHash + runtime, [])
        }
436 437 438
        /**
         * Request RM for resource
         */
439 440 441 442 443 444
        logger.info("Requesting RM " + JSON.stringify({
            resource_id,
            "memory": 332,
        }))

        resourceMap.set(resource_id, {
445
            runtime, functionHash, port: null, node_id: null,
446
            deployed: false, deploy_request_time: Date.now()
447
        })
Nilanjan Daw's avatar
Nilanjan Daw committed
448 449 450


        let payloadToRM = [{
451
            topic: constants.topics.request_dm_2_rm, // changing from REQUEST_DM_2_RM
Nilanjan Daw's avatar
Nilanjan Daw committed
452 453 454 455 456 457
            messages: JSON.stringify({
                resource_id,
                "memory": 332,
            }),
            partition: 0
        }]
458
        
Nilanjan Daw's avatar
Nilanjan Daw committed
459 460 461 462
        producer.send(payloadToRM, () => {
            // db.set(functionHash + runtime, { req, res })
            console.log("sent rm");

463
        })
464
    } else if (topic == constants.topics.response_rm_2_dm) {
Nilanjan Daw's avatar
Nilanjan Daw committed
465
        
Nilanjan Daw's avatar
Nilanjan Daw committed
466
        logger.info("Response from RM: " + message);
Nilanjan Daw's avatar
Nilanjan Daw committed
467
        message = JSON.parse(message)
Nilanjan Daw's avatar
Nilanjan Daw committed
468
        let resourceChoice = message.nodes[0]
Nilanjan Daw's avatar
Nilanjan Daw committed
469 470
        if (resourceMap.has(message.resource_id)) {
            let resource = resourceMap.get(message.resource_id)
Nilanjan Daw's avatar
Nilanjan Daw committed
471 472 473 474 475 476 477 478
            if (typeof resourceChoice === 'string') {
                resource.port = libSupport.getPort(usedPort)
                resource.node_id = resourceChoice
            } else {
                resource.port = (resourceChoice.port) ? resourceChoice.port : libSupport.getPort(usedPort)
                resource.node_id = resourceChoice.node_id
            }
            
Nilanjan Daw's avatar
Nilanjan Daw committed
479 480 481 482 483 484
            let payload = [{
                topic: resource.node_id,
                messages: JSON.stringify({
                    "type": "execute", // Request sent to Dispatch Daemon via Kafka for actual deployment at the Worker
                    resource_id: message.resource_id,
                    runtime: resource.runtime, functionHash: resource.functionHash,
485 486 487
                    port: resource.port, resources: {
                        memory: resource.memory
                    }
Nilanjan Daw's avatar
Nilanjan Daw committed
488 489 490
                }),
                partition: 0
            }]
491
            // logger.info(resourceMap);
Nilanjan Daw's avatar
Nilanjan Daw committed
492 493 494
            producer.send(payload, () => {
                logger.info(`Resource Deployment request sent to Dispatch Agent`)
            })
495
        } else {
Nilanjan Daw's avatar
Nilanjan Daw committed
496
            logger.error("something went wrong, resource not found in resourceMap")
497
        }
Nilanjan Daw's avatar
Nilanjan Daw committed
498
        
499
    }
500
});
501

502 503 504
function autoscalar() {
    functionToResource.forEach((resourceList, functionKey, map) => {
        
505 506
        if (resourceList.length > 0 && 
            resourceList[resourceList.length - 1].open_request_count > constants.autoscalar_metrics.open_request_threshold) {
507 508 509
            let resource = resourceMap.get(resourceList[resourceList.length - 1].resource_id)
            logger.warn(`resource ${resourceList[resourceList.length - 1]} exceeded autoscalar threshold. Scaling up!`)
            let payload = [{
510
                topic: constants.topics.hscale,
511 512 513 514 515 516 517 518
                messages: JSON.stringify({ "runtime": resource.runtime, "functionHash": resource.functionHash })
            }]
            producer.send(payload, function () { })
        }
    });

}

519 520 521 522 523 524 525 526 527 528
/**
 * Speculative deployment:
 * If function MLE path is present then deploy those parts of the path which are
 * not already running
 * 
 * FIXME: Currently supports homogenous runtime chain i.e takes runtime as a param. 
 * Change it to also profile runtime
 */
async function speculative_deployment(req, runtime) {
    if (constants.speculative_deployment && req.headers['x-resource-id'] === undefined) {
529
        // console.log(functionBranchTree, req.params.id);
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564

        if (functionBranchTree.has(req.params.id)) {
            let branchInfo = functionBranchTree.get(req.params.id)
            console.log("mle_path", branchInfo.mle_path);

            if (branchInfo.mle_path && branchInfo.mle_path.length > 1) {
                for (let node of branchInfo.mle_path)
                    node.id = node.node
                let metrics = await libSupport.fetchData(metricsDB + "_bulk_get", {
                    method: 'post',
                    body: JSON.stringify({
                        docs: branchInfo.mle_path
                    }),
                    headers: { 'Content-Type': 'application/json' },
                })
                console.log(util.inspect(metrics, false, null, true /* enable colors */))
                
                for (let node of branchInfo.mle_path) {
                    // console.log(functionToResource);

                    if (!functionToResource.has(node.node + runtime) && !db.has(node.node + runtime)) {
                        console.log("Deploying according to MLE path: ", node.node);

                        let payload = [{
                            topic: constants.topics.hscale,
                            messages: JSON.stringify({ "runtime": "container", "functionHash": node.node })
                        }]
                        producer.send(payload, function () { })
                        db.set(node.node + runtime, [])
                    }
                }
            }
        }
    }
}
565
setInterval(libSupport.metrics.broadcastMetrics, 5000)
566
setInterval(libSupport.viterbi, 1000, functionBranchTree)
567 568
setInterval(autoscalar, 1000);
setInterval(dispatch, 1000);
569
app.listen(port, () => logger.info(`Server listening on port ${port}!`))