explicit_chain_handler.js 19.5 KB
Newer Older
1 2 3 4 5 6 7 8
'use strict';
const express = require('express')
const libSupport = require('./lib')
const router = express.Router()
const fs = require('fs')
const { spawn } = require('child_process')
const fetch = require('node-fetch')
const constants = require('../constants.json')
9
const operator = require('./operator')
10
const sharedMeta = require('./shared_meta')
11
const util = require('util')
Nilanjan Daw's avatar
Nilanjan Daw committed
12

13 14 15
const logger = libSupport.logger

const registry_url = constants.registry_url
16 17
let functionToResource = sharedMeta.functionToResource,
    db = sharedMeta.db,
18
    conditionProbabilityExplicit = sharedMeta.conditionProbabilityExplicit,
19 20

    metricsDB = sharedMeta.metricsDB,
21 22
    metadataDB = sharedMeta.metadataDB,
    explicitChainDB = sharedMeta.explicitChainDB
23 24


25 26 27 28 29 30 31 32 33 34
router.post('/deploy', (req, res) => {
    
    // let runtime = req.body.runtime
    let files = req.files

    const chain_id = libSupport.makeid(constants.id_size)
    const file_path = __dirname + "/repository/"
    let aliases = {}
    let deployHandles = []
    createDirectory(file_path).then(() => {
35
        
36 37
        for (const [file_alias, file] of Object.entries(files)) {
            let functionHash = file.md5
38 39 40 41 42 43
            if (file_alias === 'map') {
                    file.mv(file_path + 'map' + chain_id + ".json")
                    continue     
            }
            // aliases[file_alias] = functionHash
            deployHandles.push(deploy(file_path, functionHash, file, aliases, file_alias))
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
        }

        console.log("aliases", aliases);
        Promise.all(deployHandles).then(() => {
            console.log("done");
            fs.writeFile(file_path + `aliases${chain_id}.json`, JSON.stringify(aliases, null, 2), function(err) {
                res.json({
                    status: "success",
                    function_id: chain_id
                })
            })
            
        }).catch(err => {
            res.json({
                status: "error",
                reason: err
            }).status(400)
        })
    })
   
})

66
async function deploy(file_path, functionHash, file, aliases, file_alias) {
67 68 69 70
    let runtime = "container", memory = 330
    try {
        await moveFile(file, file_path, functionHash)
        functionHash = libSupport.generateExecutor(file_path, functionHash)
71
        aliases[file_alias] = functionHash
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
        /**
         * Adding meta caching via couchdb
         * This will create / update function related metadata like resource limits etc
         * on a database named "serverless".
         */
        let res = await fetch(metadataDB + functionHash)
        let json = await res.json()
        console.log(json);
        
        if (json.error === "not_found") {
            logger.warn("New function, creating metadata")
            await fetch(metadataDB + functionHash, {
                method: 'put',
                body: JSON.stringify({
                    memory: memory
                }),
                headers: { 'Content-Type': 'application/json' },
            })
            // let json = await res.json()
            // console.log(json)
        } else {
            logger.warn('Repeat deployment, updating metadata')
            try {
                await fetch(metadataDB + functionHash, {
                    method: 'put',
                    body: JSON.stringify({
                        memory: memory,
                        _rev: json._rev
                    }),
                    headers: { 'Content-Type': 'application/json' },
                })
                // let json = await res.json()
                // console.log(json)
            } catch (err) {
                console.log(err);
                
            }
        }

        if (runtime === "container") {
            try {
                await deployContainer(file_path, functionHash)
                console.log("called");
115
                return Promise.resolve(functionHash)
116 117 118 119
            } catch(err) {
                return Promise.reject(err)
            }
        } else {
120
            return Promise.resolve(functionHash)
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        }
    } catch (err) {
        logger.error(err)
        return Promise.reject(err)
    }
}

function moveFile(file, file_path, functionHash) {
    return new Promise((resolve, reject) =>{ 
        file.mv(file_path + functionHash, function (err) {
            if (err)
                reject(err)
            resolve()
        })
    })
}

async function deployContainer(path, imageName) {
    return new Promise((resolve, reject) => {
        let buildStart = Date.now()

        fs.writeFile('./repository/Dockerfile' + imageName,
            `FROM node:latest
            WORKDIR /app
            COPY ./worker_env/package.json /app
            ADD ./worker_env/node_modules /app/node_modules
            COPY ${imageName}.js /app
            ENTRYPOINT ["node", "${imageName}.js"]`
            , function (err) {
                if (err) {
                    logger.error("failed", err);


                    reject(err);
                }
                else {
                    logger.info('Dockerfile created');
                    const process = spawn('docker', ["build", "-t", registry_url + imageName, path, "-f", path + `Dockerfile${imageName}`]);

                    process.stdout.on('data', (data) => {
                        logger.info(`stdout: ${data}`);

                    });

                    process.stderr.on('data', (data) => {
                        logger.error(`stderr: ${data}`);
                    });

                    process.on('close', (code) => {
                        logger.warn(`child process exited with code ${code}`);
                        let timeDifference = Math.ceil((Date.now() - buildStart))
                        logger.info("image build time taken: ", timeDifference);
                        const process_push = spawn('docker', ["push", registry_url + imageName]);

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

                        });

                        process_push.stderr.on('data', (data) => {
                            logger.error(`stderr: ${data}`);
                        });

                        process_push.on('close', (code) => {
                            logger.info("image pushed to repository");
                            resolve();
                        })

                    });
                }
            });
    })
}

195 196
router.post('/execute/:id', (req, res) => {
    let map, aliases
197
    let chain_id = req.params.id
198 199 200
    libSupport.fetchData(explicitChainDB + chain_id)
    .then(chainData => {
        console.log(chainData);
201 202 203 204 205 206
        let path = {
            path: [],
            onPath: true,
            dependency: {},
            level: 0
        }
207 208
        if (chainData.error !== "not_found")
            conditionProbabilityExplicit[chain_id] = chainData
209 210
        else
            conditionProbabilityExplicit[chain_id] = {}
211 212 213
        if (req.files && req.files.map) {
            map = JSON.parse(req.files.map.data.toString());
            readMap(`./repository/aliases${chain_id}.json`, true)
214 215 216
            .then(data => {
                aliases = data
                let payload = JSON.parse(req.body.data)
217 218 219
                if (chainData.error != "not_found")
                    speculative_deployment(chain_id, aliases, chainData);
                orchestrator(chain_id, res, payload, map, aliases, {}, path)
220
            })
221 222
        } else {
            readMap(`./repository/map${chain_id}.json`)
223 224
            .then(data => {
                map = data
225

226
                readMap(`./repository/aliases${chain_id}.json`, true)
227 228 229
                    .then(data => {
                        aliases = data
                        let payload = JSON.parse(req.body.data)
230 231 232
                        if (chainData.error != "not_found")
                            speculative_deployment(chain_id, aliases, chainData);
                        orchestrator(chain_id, res, payload, map, aliases, {}, path)
233 234
                    })
            })
235 236
        }
    })
237
    
238 239
})

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
/**
 * Orchestrator function to execute a chain and return the result to the invoker
 * @param {string} chain_id ID of the chain to be executed
 * @param {JSON} res response object
 * @param {JSON} payload data to be passed to the chain
 * @param {JSON} map holds the chain map
 * @param {JSON} aliases internal alias to function chain mapping
 * @param {JSON} result result obtained after chain executes
 */
async function orchestrator(chain_id, res, payload, map, aliases, result, path) {

    /**
     * Adding dependencies on MLE path to a map
     * for fast lookup during speculation
     */
    for (const [functionName, metadata] of Object.entries(map)) {
        if (metadata.type === "function" || metadata.type === "conditional") {
            if (path.dependency[functionName] === undefined)
                path.dependency[functionName] = JSON.parse(JSON.stringify(metadata.wait_for))
        }
    }
261

262 263 264
    if (Object.keys(map).length == 0) {
        console.log("time to resolve", result);
        res.json(result)
265 266
        if (path.onPath)
            conditionProbabilityExplicit[chain_id]["path"] = path
267 268 269 270 271 272
        let payload = {
            method: 'put',
            body: JSON.stringify(conditionProbabilityExplicit[chain_id]),
            headers: { 'Content-Type': 'application/json' }
        }
        libSupport.fetchData(explicitChainDB + chain_id, payload)
273 274
        console.log("detected path", util.inspect(path, false, null, true /* enable colors */));
        
275 276 277 278 279
        // return resolve(result)
    }
        
    else {
        for (const [functionName, metadata] of Object.entries(map)) {
280
            
281 282 283 284 285 286 287 288 289
            if (metadata.type === "function" && metadata.wait_for.length == 0) {
                let url = `http://${constants.master_address}:${constants.master_port}/serverless/execute/${aliases[functionName].alias}`
                console.log(url);
                let data = {
                    method: 'post',
                    body: JSON.stringify({
                        runtime: metadata.runtime,
                        payload
                    }),
290
                    headers: { 'Content-Type': 'application/json', 'x-chain-type': 'explicit' }
291 292 293
                }
                delete map[functionName]
                aliases[functionName].status = "running"
294 295 296
                if (typeof path.path[path.level] === 'undefined') {
                    path.path[path.level] = []
                }
297
                
298
                path.path[path.level].push({functionName, type: "function", runtime: metadata.runtime})
299
                libSupport.fetchData(url, data)
300 301 302 303 304
                    .then(json => {
                        // console.log(json);
                        result[functionName] = json
                        
                        aliases[functionName].status = "done"
305
                        let branchMap = null, flag = false
306
                        for (const [_key, metadata] of Object.entries(map)) {
307

308 309
                            if (metadata.type === "function" || metadata.type === "conditional") {
                                let index = metadata.wait_for.indexOf(functionName)
310 311
                                if (index >= 0)
                                    metadata.wait_for.splice(index, 1);
312 313
                                if (metadata.wait_for.length == 0)
                                    flag = true // something is runnable
314
                            }
315 316 317
                            if (metadata.type === "conditional" && metadata.wait_for.length == 0) {
                                
                                let conditionResult = checkCondition(metadata.condition.op1, metadata.condition.op2, metadata.condition.op, result)
318 319 320 321
                                if (conditionProbabilityExplicit[chain_id] === undefined)
                                    conditionProbabilityExplicit[chain_id] = {}
                                if (conditionProbabilityExplicit[chain_id][_key] === undefined)
                                    conditionProbabilityExplicit[chain_id][_key] = {
322 323 324
                                        request_count: 0,
                                        probability: 0
                                    }
325
                                let oldProbability = conditionProbabilityExplicit[chain_id][_key].probability
326
                                let updateProbability = (conditionResult === 'success') ? 1.0 : 0.0
327 328 329 330 331 332
                                conditionProbabilityExplicit[chain_id][_key].probability = 
                                    oldProbability * conditionProbabilityExplicit[chain_id][_key].request_count + updateProbability
                                conditionProbabilityExplicit[chain_id][_key].request_count++
                                conditionProbabilityExplicit[chain_id][_key].probability /=
                                         conditionProbabilityExplicit[chain_id][_key].request_count
                                console.log(conditionResult, "probability table", conditionProbabilityExplicit);
333 334 335 336
                                let branchToTake = metadata[conditionResult]
                                branchMap = map[branchToTake]
                                delete map[_key]
                                makeBranchRunnable(branchMap, aliases)
337 338 339 340 341 342 343 344 345
                                if ((conditionResult === 'success') && conditionProbabilityExplicit[chain_id][_key].probability < 0.5 ||
                                    (conditionResult !== 'success') && conditionProbabilityExplicit[chain_id][_key].probability > 0.5) {
                                    path.onPath = false
                                    console.log("out of path");   
                                }
                                path.level++
                                if (typeof path.path[path.level] === 'undefined') {
                                    path.path[path.level] = []
                                }
346
                                
347
                                path.path[path.level].push({functionName: _key, type: "condition"})
348 349
                            }
                        }
350 351 352
                        if (flag)
                            path.level++
                        orchestrator(chain_id, res, payload, (branchMap == null)? map: branchMap, aliases, result, path)
353
                    })
354 355
            }
        }
356 357 358
    }
}

359 360 361 362 363 364
/**
 * Make the branch runnable by removing redundant dependencies in the map 
 * which have already executed
 * @param {JSON} branchMap sub map of the chain holding the branch to be executed
 * @param {JSON} aliases internal alias to function chain mapping
 */
365 366 367
function makeBranchRunnable(branchMap, aliases) {
    delete branchMap['type']
    for (const [_key, metadata] of Object.entries(branchMap)) {
Nilanjan Daw's avatar
Nilanjan Daw committed
368 369 370 371 372 373 374
        if (metadata.type === "function" || metadata.type === "conditional") {
            let wait_for = []
            for (const dependent of metadata.wait_for) {
                if (aliases[dependent].status !== "done")
                    wait_for.push(dependent)
                metadata.wait_for = wait_for
            }
375 376 377 378 379 380 381 382 383 384
        }
    }
}

function checkCondition(op1, op2, op, result) {
    op1 = op1.split(".")
    let data = result[op1[0]][op1[1]]
    return (operator[op](data, op2))? "success": "fail"
}

385 386 387 388 389 390 391 392 393 394 395 396
async function speculative_deployment(chain_id, aliases, chainData) {
    // console.log("chainData", util.inspect(chainData, false, null, true /* enable colors */));
    let plan = []
    let path = chainData.path.path
    if (constants.speculative_deployment) {
        for (let i = 0; i < path.length; i++) {
            for (const node of path[i]) {
                if (node.type === "function") {
                    node.id = aliases[node.functionName].alias
                    node.invokeTime = 0
                    // console.log(node);
                    plan.push(node)
397
                }
398
            }
399
        }
400

401
        if (constants.JIT_deployment) {
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
            let conditionalDelay = 0, metricsData = new Map(), delayMap = new Map()
            let data = await libSupport.fetchData(metricsDB + "_bulk_get", {
                method: 'post',
                body: JSON.stringify({
                    docs: plan
                }),
                headers: { 'Content-Type': 'application/json' },
            })
            data = data.results
            for (let i = 0; i < path.length; i++) {
                let id = data[i].id
                metricsData[id] = data[i].docs[0].ok
            }
            // console.log(metricsData);
            for (let i = 0; i < path.length; i++) {
                for (const node of path[i]) {
                    let maxDelay = conditionalDelay
                    for (const dependency of chainData.path.dependency[node.functionName]) {
                        if (delayMap.get(dependency) > maxDelay)
                            maxDelay = delayMap.get(dependency)
                    }
                    if (maxDelay == 0) {
                        maxDelay += (node.type === "function")? metricsData[node.id][node.runtime].coldstart: 0
                        delayMap.set(node.functionName, maxDelay)
                    } else {
                        if (node.type === "function")
                            node.invokeTime = maxDelay - metricsData[node.id][node.runtime].starttime
                        maxDelay += (node.type === "function")? metricsData[node.id][node.runtime].warmstart: 0
                        delayMap.set(node.functionName, maxDelay)
                    }
                    if (node.type === "condition")
                        conditionalDelay = maxDelay
Nilanjan Daw's avatar
Nilanjan Daw committed
434
                }
435 436 437 438
            }
            console.log("delay map", delayMap);
            console.log("notifcation plan", plan);
        }
439
        let counter = 0, maxCount = plan.length * constants.aggressivity
440
        for (const node of plan) {
441 442
            if (counter > maxCount)
                break
443 444
            console.log("notification set for", node.functionName);
            setTimeout(notify, node.invokeTime, node.runtime, node.id)
445
            counter++
446
        }
447
    }
448 449
}

450
function readMap(filename, alias = false) {
451
    return new Promise((resolve, reject) => {
452
        fs.readFile(filename, (err, blob) => {
453 454 455
            if (err)
                reject(err)
            else {
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
                const data = JSON.parse(blob)
                if (alias) {
                    for (const [key, functionHash] of Object.entries(data)) {
                        data[key] = {
                            alias: functionHash,
                            status: "waiting"
                        }

                        // libSupport.fetchData(metricsDB + functionHash, null)
                        // .then(metrics => {
                        //     data[key]
                        // })
                    }
                }
                resolve(data)
471 472 473 474 475
            }
        })
    })
}

476
function notify(runtime, functionHash) {
477
    // console.log("check map: ", functionToResource.has(functionHash + runtime));
478 479 480 481 482 483 484 485 486 487
    if (!functionToResource.has(functionHash + runtime) && !db.has(functionHash + runtime)) {
        let payload = [{
            topic: constants.topics.hscale,
            messages: JSON.stringify({ runtime, functionHash })
        }]
        libSupport.producer.send(payload, function () { })
    } else {
        console.log("resource already present: skipping speculation");
        
    }
488 489
}

490 491 492 493 494 495 496 497 498 499 500 501 502 503
function createDirectory(path) {
    return new Promise((resolve, reject) => {
        if (!fs.existsSync(path)) {
            fs.mkdir(path, err => {
                if (err)
                    reject();
                resolve();
            })
        } else {
            resolve();
        }
    })
}

504 505

module.exports = {
506
    router, notify
507
}