目录

Custom Runtime

入口方法

入口方法定义如下所示:

日志记录

获取环境变量

Custom Runtime运行环境下,获取环境变量的方法,与开发者上传的工程项目里使用的编程语言所对应的获取环境变量的方法有关。

示例如下:

异常处理

根据自定义运行时的内置运行环境,使用对应语言的异常处理方式即可。

函数示例

[h2]Node.js 20.x

/**
 * Describe the basic method of Cloud Functions
 */

const express = require('express');
const log4js = require("log4js");
const app = express();

let runJsonLogger = logEvent => {
    let logInfo = {
        M: logEvent.data[0] || "",
        T: logEvent.startTime,
        L: logEvent.level.levelStr,
        TRACE: logEvent.data[1], // logger若有第二个参数,需要设置为traceid
    };

    return JSON.stringify(logInfo);
};
log4js.addLayout("runjson", () => {
    return runJsonLogger;
});
let logConfig = {
    replaceConsole: true,
    appenders: {
        'out': {
            type: 'stdout',
            layout: {
                type: "colored"
            }
        },
        'files': {
            type: 'file',
            filename: '/opt/huawei/logs/logs.log',
            layout: {
                "type": "runjson",
                "pattern": "%x{showDate}|%m"
            }
        }
    },
    categories: {
        default: {
            appenders: ['out', 'files'],
            level: "INFO"
        }
    },
    disableClustering: true
}
log4js.configure(logConfig);
const logger = log4js.getLogger('CUSTOM-RUNTIME-NODEJS-DEMO-LOG');

app.post('/invoke', function (req, res) {
    // example of display environment variables
    let env1 = process.env.env1;

    // example of display logs
    logger.info("Test info log");
    logger.warn("Test warn log");
    logger.debug("Test debug log");
    logger.error("Test error log");

    logger.info("--------Start-------");
    try {
        let startTime = new Date().getTime();
        let endTime = startTime;
        let interval = 0;
        startTime = process.uptime() * 1000;

        // print input parameters and environment variables
        logger.info("req: " + req.query);
        logger.info("env1: " + env1);

        endTime = process.uptime() * 1000;
        interval = endTime - startTime;
        logger.info("intervalTime: " + interval);
        logger.info("--------Finished-------");

        let result = {"intervalTime": interval};
        res.send(JSON.stringify(result));
    } catch (error) {
        logger.error("--------Error-------");
        logger.error("error: " + error);
        res.send(error);
    }
});

app.listen(9000, function () {
    logger.info("---------server start now!-------");
});

[h2]Java 1.8

package com.example.demo;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
@RestController
public class Application {
    private static final Logger LOG = LoggerFactory.getLogger("com.huawei.customedemo");

    public static void main(String[] args) {
        LOG.info("start spring server now!");
        try {
            ClasspathLoader.loadClassPath();
        } catch (MyException e) {
            LOG.error("failed to load layer " + e.getMessage());
        }
        SpringApplication.run(Application.class, args);
    }

    @RequestMapping(path = "/invoke", method = RequestMethod.POST)
    public Object postSimple(HttpServletRequest req,  @RequestBody JSONObject body) {
        // example of display environment variables
        String env = System.getenv("env1");

        // example of display logs
        LOG.info("Test info log");
        LOG.warn("Test warn log");
        LOG.debug("Test debug log");
        LOG.error("Test error log");

        LOG.info("----------Start-----------");
        JSONObject result = new JSONObject();
        result.put("code", 0);
        try {
            long interval;
            long startTime = System.currentTimeMillis();

            LOG.info("receive post request");
            String query=req.getQueryString();
            String hwm=req.getHeader("hwm");
            Map<String,String[]> params =req.getParameterMap();
            String config=PropertyUtil.getProperty("key.rootkey.path");

            LOG.info("query :"+query);
            LOG.info("headers :"+hwm);
            LOG.info("params :"+JSONObject.toJSONString(params));
            LOG.info("body :"+body.toJSONString());
            LOG.info("config :"+config);

            long endTime = System.currentTimeMillis();
            interval = endTime - startTime;
            LOG.info("intervalTime: " + interval + "(ms)");
            result.put("intervalTime: ", interval + "(ms)");
            LOG.info("--------Finished---------");
        } catch (Exception e) {
            LOG.error("the ex is " + e.getMessage());
            result.put("msg", e.getMessage());
        }
        return result ;
    }
}

[h2]Python 3.11

"""
Describe the basic method of Cloud Functions
"""

import os
import sys
import time
from run import runtime_run_log as run_log

sys.path.append('python_modules')
from flask import Flask, request

app = Flask(__name__)

@app.route("/invoke", methods=["POST"])
def simple_fn():
    try:
        # example of display environment variables
        env1 = os.environ.get("env1")

        # example of display logs
        run_log.info("Test info log")
        run_log.debug("Test debug log")
        run_log.warning("Test warning log")
        run_log.error("Test error log")

        run_log.info("-------------Start--------------")
        startTime = int(time.time())

        # print input parameters and environment variables
        query = request.query_string.decode('utf-8')
        
        run_log.info("request: " + repr(query))
        headers = request.headers
        
        run_log.info("headers: " + str(headers))
        body = request.data.decode('utf-8')
        run_log.info("body: " + str(body))
        run_log.info("env1: " + env1)
        

        endTime = int(time.time())
        interval = endTime - startTime
        run_log.info("intervalTime: " + str(interval))
        run_log.info("-------------Finished--------------")

        return request.method + " success"
    except Exception as error:
        run_log.error("error: " + format(str(error)))
        return request.method + format(str(error))

if __name__ == '__main__':
    app.run(port=9000)

准备函数部署包

使用Node.js开发Custom Runtime函数部署包示例:nodejs.zip

Java1.8 函数部署包示例:java.zip

Python3 函数部署包示例:python.zip

Custom Runtime函数部署包结构如下所示,bootstrap可执行文件必须在zip根目录下,其他相关代码和依赖项可以自由放置。

function.zip
   |---bootstrap //可执行文件,启动Server
   |---WiseFunctionCustomDemo.jar
   |---其他相关代码和依赖等

bootstrap文件内容示例:

#!/bin/bash 
java -jar WiseFunctionCustomDemo.jar