explicit_chain_handler.js 19.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 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 115 116 117 118 119 120 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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
'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')
const operator = require('./operator')
const sharedMeta = require('./shared_meta')
const util = require('util')

const logger = libSupport.logger

const registry_url = constants.registry_url
let functionToResource = sharedMeta.functionToResource,
    db = sharedMeta.db,
    conditionProbabilityExplicit = sharedMeta.conditionProbabilityExplicit,

    metricsDB = sharedMeta.metricsDB,
    metadataDB = sharedMeta.metadataDB,
    explicitChainDB = sharedMeta.explicitChainDB


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(() => {
        
        for (const [file_alias, file] of Object.entries(files)) {
            let functionHash = file.md5
            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))
        }

        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)
        })
    })
   
})

async function deploy(file_path, functionHash, file, aliases, file_alias) {
    let runtime = "container", memory = 330
    try {
        await moveFile(file, file_path, functionHash)
        functionHash = libSupport.generateExecutor(file_path, functionHash)
        aliases[file_alias] = functionHash
        /**
         * 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");
                return Promise.resolve(functionHash)
            } catch(err) {
                return Promise.reject(err)
            }
        } else {
            return Promise.resolve(functionHash)
        }
    } 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();
                        })

                    });
                }
            });
    })
}

router.post('/execute/:id', (req, res) => {
    let map, aliases
    let chain_id = req.params.id
    libSupport.fetchData(explicitChainDB + chain_id)
    .then(chainData => {
        console.log(chainData);
        let path = {
            path: [],
            onPath: true,
            dependency: {},
            level: 0
        }
        if (chainData.error !== "not_found")
            conditionProbabilityExplicit[chain_id] = chainData
        else
            conditionProbabilityExplicit[chain_id] = {}
        if (req.files && req.files.map) {
            map = JSON.parse(req.files.map.data.toString());
            readMap(`./repository/aliases${chain_id}.json`, true)
            .then(data => {
                aliases = data
                let payload = JSON.parse(req.body.data)
                if (chainData.error != "not_found")
                    speculative_deployment(chain_id, aliases, chainData);
                orchestrator(chain_id, res, payload, map, aliases, {}, path)
            })
        } else {
            readMap(`./repository/map${chain_id}.json`)
            .then(data => {
                map = data

                readMap(`./repository/aliases${chain_id}.json`, true)
                    .then(data => {
                        aliases = data
                        let payload = JSON.parse(req.body.data)
                        if (chainData.error != "not_found")
                            speculative_deployment(chain_id, aliases, chainData);
                        orchestrator(chain_id, res, payload, map, aliases, {}, path)
                    })
            })
        }
    })
    
})

/**
 * 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))
        }
    }

    if (Object.keys(map).length == 0) {
        console.log("time to resolve", result);
        res.json(result)
        if (path.onPath)
            conditionProbabilityExplicit[chain_id]["path"] = path
        let payload = {
            method: 'put',
            body: JSON.stringify(conditionProbabilityExplicit[chain_id]),
            headers: { 'Content-Type': 'application/json' }
        }
        libSupport.fetchData(explicitChainDB + chain_id, payload)
        console.log("detected path", util.inspect(path, false, null, true /* enable colors */));
        
        // return resolve(result)
    }
        
    else {
        for (const [functionName, metadata] of Object.entries(map)) {
            
            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
                    }),
                    headers: { 'Content-Type': 'application/json', 'x-chain-type': 'explicit' }
                }
                delete map[functionName]
                aliases[functionName].status = "running"
                if (typeof path.path[path.level] === 'undefined') {
                    path.path[path.level] = []
                }
                
                path.path[path.level].push({functionName, type: "function", runtime: metadata.runtime})
                libSupport.fetchData(url, data)
                    .then(json => {
                        // console.log(json);
                        result[functionName] = json
                        
                        aliases[functionName].status = "done"
                        let branchMap = null, flag = false
                        for (const [_key, metadata] of Object.entries(map)) {

                            if (metadata.type === "function" || metadata.type === "conditional") {
                                let index = metadata.wait_for.indexOf(functionName)
                                if (index >= 0)
                                    metadata.wait_for.splice(index, 1);
                                if (metadata.wait_for.length == 0)
                                    flag = true // something is runnable
                            }
                            if (metadata.type === "conditional" && metadata.wait_for.length == 0) {
                                
                                let conditionResult = checkCondition(metadata.condition.op1, metadata.condition.op2, metadata.condition.op, result)
                                if (conditionProbabilityExplicit[chain_id] === undefined)
                                    conditionProbabilityExplicit[chain_id] = {}
                                if (conditionProbabilityExplicit[chain_id][_key] === undefined)
                                    conditionProbabilityExplicit[chain_id][_key] = {
                                        request_count: 0,
                                        probability: 0
                                    }
                                let oldProbability = conditionProbabilityExplicit[chain_id][_key].probability
                                let updateProbability = (conditionResult === 'success') ? 1.0 : 0.0
                                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);
                                let branchToTake = metadata[conditionResult]
                                branchMap = map[branchToTake]
                                delete map[_key]
                                makeBranchRunnable(branchMap, aliases)
                                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] = []
                                }
                                
                                path.path[path.level].push({functionName: _key, type: "condition"})
                            }
                        }
                        if (flag)
                            path.level++
                        orchestrator(chain_id, res, payload, (branchMap == null)? map: branchMap, aliases, result, path)
                    })
            }
        }
    }
}

/**
 * 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
 */
function makeBranchRunnable(branchMap, aliases) {
    delete branchMap['type']
    for (const [_key, metadata] of Object.entries(branchMap)) {
        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
            }
        }
    }
}

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

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)
                }
            }
        }

        if (constants.JIT_deployment) {
            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
                }
            }
            console.log("delay map", delayMap);
            console.log("notifcation plan", plan);
        }
        let counter = 0, maxCount = plan.length * constants.aggressivity
        for (const node of plan) {
            if (counter > maxCount)
                break
            console.log("notification set for", node.functionName);
            setTimeout(notify, node.invokeTime, node.runtime, node.id)
            counter++
        }
    }
}

function readMap(filename, alias = false) {
    return new Promise((resolve, reject) => {
        fs.readFile(filename, (err, blob) => {
            if (err)
                reject(err)
            else {
                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)
            }
        })
    })
}

function notify(runtime, functionHash) {
    // console.log("check map: ", functionToResource.has(functionHash + runtime));
    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");
        
    }
}

function createDirectory(path) {
    return new Promise((resolve, reject) => {
        if (!fs.existsSync(path)) {
            fs.mkdir(path, err => {
                if (err)
                    reject();
                resolve();
            })
        } else {
            resolve();
        }
    })
}


module.exports = {
    router, notify
}