IBM Cloud Docs
从本地源代码创建函数工作负载

从本地源代码创建函数工作负载

您可以使用 IBM Cloud® Code Engine CLI 直接从本地工作站上的源代码创建 Code Engine 函数。 使用 function create (或 fn create) 命令可从本地源构建代码束,并部署函数以引用此已构建的代码束。

代码束是表示函数代码的文件的集合。 此代码束将注入到运行时容器中。 代码束由 Code Engine 创建,并存储在容器注册表中或与函数直接插入。 代码束不是开放式容器计划 (OCI) 标准容器映像。

提交从本地目录中提取代码的构建时,源代码将打包到归档文件中。Code Engine 自动将代码束上载到帐户中的 IBM Cloud® Container Registry 名称空间,然后创建并部署函数以引用此构建的代码束。 请注意,只能将 IBM Cloud Container Registry 作为本地构建的目标。 对于此场景,您只需要提供函数的名称以及本地源的路径。 有关选项的完整列表,请参阅 ibmcloud ce fn create 命令。

有关访问映像注册表所需的许可权的信息,请参阅 设置映像注册表的权限

您可以选择通过使用 .ceignore 文件来忽略源代码中的某些文件模式,该文件的行为与 .gitignore 文件类似。 例如,Node.js 函数的 .ceignore 文件的条目可能包括 node_modules.npm。 有关要忽略的更多样本文件模式,请参阅 GitHub.gitignore 存储库

此方案需要 IBM Cloud® Container Registry。

准备工作

在使用本地源之前,请确保源位于本地工作站上的可访问位置。

使用 CLI 从本地源代码创建函数

此示例使用保存为 main.js 文件的以下 Node.js 代码。 您可以替换自己的代码。

/**
 * The `main` function is the entry-point into the function.
 * It has one optional argument, which carries all the
 * parameters the function was invoked with.
*/
async function main(params) {
  // log environment variables available to the function
  console.log(process.env);
  // log Code Engine system headers available to the function
  console.log(params.__ce_headers);
  // log all parameters for debugging purposes
  console.log("params: "+params);
  // since functions are invoked through http(s), we return an HTTP response
  return {
      statusCode: 200,
      headers: { 'Content-Type': 'application/json' },
      body: params };
}

// this step is necessary, if you gave your main function a different name
// we include it here for documentation purposes only
module.exports.main = main;
  1. 切换到包含 main.js 文件的目录,或者记录该文件的路径。

  2. 创建一个名为 myfun-local 的函数,该函数使用 main.js 文件作为源。 此命令会自动构建代码束并将其推送到帐户中的 Container Registry 名称空间。 如果您没有现有的 Container Registry 名称空间,那么 Code Engine 会自动为您创建一个名称空间。

    ibmcloud ce fn create --name myfun-local --runtime nodejs-20 --build-source main.js
    

    示例输出

    Preparing function 'myfun-local' for build push...
    Creating function 'myfun-local'...
    Packaging files to upload from source path 'main.js'...
    Submitting build run 'myfun-local-run-230123-111011111'...
    Creating image 'icr.io/ce--abcde-glxo4kabcde/function-myfun-local:230123-1650-yrj86'...
    Waiting for build run to complete...
    Build run status: 'Running'
    Build run completed successfully.
    Run 'ibmcloud ce buildrun get -n myfun-local-run-230626-115011911' to check the build run status.
    Waiting for function 'myfun-local' to become ready...
    Function 'myfun-local' is ready.
    OK
    Run 'ibmcloud ce function get -n myfun-local' to see more details.
    
    https://myfun-local.glxo4kabcde.us-south.codeengine.test.appdomain.cloud
    

    请注意,function create 命令的输出提供了有关在创建函数之前构建运行的进度的信息。

    在此示例中,已构建的代码束将上载到 Container Registry中的 ce--abcde-glxo4kabcde 名称空间。

    下表概述了此示例中与 fn create 命令配合使用的选项。 有关该命令及其选项的更多信息,请参阅 ibmcloud ce function create 命令。 由于这些选项因源代码所在位置而异,请确保源代码所在位置与示例相符。

    命令描述
    选项 描述
    --name 函数的名称。 请使用项目中唯一的名称。 此值是必需的。
    -名称必须以小写字母开头。
    -名称必须以小写字母数字字符结尾。
    -名称必须不超过 63 个字符,并且可以包含字母,数字和连字符 (-)。
    --build-source 通往当地水源的道路。 此值是必需的。
    --runtime 要用于此功能的运行时。 此值是必需的。
  3. 使用 function get 命令可显示有关应用程序的信息,包括有关构建的信息。

    ibmcloud ce function get --name myfun-local
    

    示例输出

    Getting function 'myfun-local'...
    OK
    
    Name:          myfun-local
    Project Name:  sample
    Project ID:    abcdefgh-abcd-abcd-abcd-1a2b3c4d5e6f
    Age:           5m41s
    Created:       2023-06-26T16:50:14Z
    URL:           https://myfun-local.glxo4kabcde.us-south.codeengine.test.appdomain.cloud
    Status:        Ready
    
    Resources:
      CPU:                 0.25
      Memory:              500M
      Max Execution Time:  60 seconds
    
    Build Information:
      Build Run Name:     myfun-local-run-230123-111011111
      Build Type:         local
      Build Strategy:     codebundle-nodejs-20
      Timeout:            600
      Source:             main.js
    
      Build Run Summary:  Succeeded
      Build Run Status:   Succeeded
      Build Run Reason:   All Steps have completed executing
      Run 'ibmcloud ce buildrun get -n myfun-local-run-230123-111011111' for details.
    
    Function Code:
      Runtime:        nodejs-20 (managed)
      Bundle Secret:  ce-auto-icr-us-south
      Code Bundle:    cr://icr.io/ce--abcde-glxo4kabcde/function-myfun-local:230123-1650-yrj86
      Main:           main()
    

包含函数的依赖关系

您可以使用许多不同的编程语言创建函数。 当函数代码变得复杂时,您可以添加代码模块作为函数的依赖项。 每种语言都有自己的模块可与您的函数代码配合使用。 例如,Node.js 依赖关系通常是现有 npm 模块,而 Python 使用 Python 包。 必须使用源代码在文件中声明和创建这些依赖关系

包含 Node.js 函数的模块

通过创建 package.json 文件来创建包含特定 Node.js 模块依赖关系的函数。 在这种情况下,源代码和包文件都位于同一文件夹中。

  1. 通过将代码写入 main.js 文件来创建源代码。 例如,将以下代码示例复制到名为 main.js 的文件中。

    /**
    * The `main` function is the entry-point into the function.
    * It has one optional argument, which carries all the
    * parameters the function was invoked with.
    */
    function main(params /* optional */) {
      // use third-party 'lorem-ipsum' package to generate random words
      const LoremIpsum = require("lorem-ipsum").LoremIpsum;
      const lorem = new LoremIpsum();
    
      // since functions are invoked through http(s), we return an HTTP response
      return {
        headers: { "Content-Type": "text/plain;charset=utf-8" },
        body: lorem.generateWords(10),
      };
    }
    
    // this step is necessary, if you gave your main function a different name
    // we include it here for documentation purposes only
    module.exports.main = main;
    
  2. 创建包含函数的必需依赖关系的 package.json 文件。 对于先前的代码示例,请对 package.json 文件使用以下内容。

    {
      "name": "function",
      "version": "1.0.0",
      "main": "main.js",
      "dependencies" : {
    		    "lorem-ipsum" : "2.0.8"
     	}
    }
    
  3. 在 Code Engine中创建文件作为函数。 在这种情况下,您位于本地文件所在的目录中,因此可以使用 . 作为构建源。

    ibmcloud ce fn create --name nodelorem --runtime nodejs-20 --build-source .
    
  4. 运行提供的 fn get 命令以查找有关功能的详细信息。

  5. 将 URL 粘贴到浏览器中即可调用您的功能。 您的浏览器显示 lorem ipsum 的段落。

有关 fn create 命令及其选项的更多信息,请参阅 创建函数

包含 Python 函数的模块

通过创建 requirements.txt 文件来创建包含特定 Python 模块依赖关系的函数。 在这种情况下,源代码和需求文件都位于同一文件夹中。

  1. 通过将代码保存到 __main__.py 文件来创建函数

    # use third-party 'lorem-ipsum' package to generate random words
    from lorem_text import lorem
    
    # The `main` function is the entry-point into the function.
    # It has one optional argument, which carries all the
    # parameters the function was invoked with.
    def main(params):
        words = 10
    
        # since functions are invoked through http(s), we return an HTTP response
        return {
          "headers": {
            "Content-Type": "text/plain;charset=utf-8",
        },
        "body": lorem.words(words),
    }
    def main(params):
         words = 10
    
         return {
              "headers": {
                  "Content-Type": "text/plain;charset=utf-8",
              },
              "body": lorem.words(words),
          }
    
  2. 创建包含函数的必需依赖关系的 requirements.txt

    lorem-text
    
  3. 在 Code Engine中创建文件作为函数。 在这种情况下,您位于本地文件所在的目录中,因此可以使用 . 作为构建源。

    ibmcloud ce fn create --name pylorem --runtime python-3.11 --build-source .
    
  4. 运行提供的 fn get 命令以查找有关功能的详细信息。

  5. 将 URL 粘贴到浏览器中即可调用您的功能。 您的浏览器显示 lorem ipsum 的段落。

有关 fn create 命令及其选项的更多信息,请参阅 创建函数

后续步骤

现在,您的函数是从本地源代码创建和部署的,您可以使用 ibmcloud ce function update 命令来更新函数以满足您的需求。 如果要更新源以用于功能,那么必须在 function update 命令上提供 --build-source 选项。

从本地源或从 CLI 的 存储库源代码 部署函数时,生成的构建运行不基于构建配置。 最终会自动删除完成的构建运行。 如果构建运行成功,那么将在 1 小时后删除不基于构建配置的构建运行。 如果构建运行不成功,那么将在 24 小时后删除此构建运行。 只能使用 CLI 显示有关此构建运行的信息。 您无法在控制台中查看此构建运行。

要查找更多代码示例吗? 请查看 样本 IBM Cloud Code Engine GitHub 存储库