Start collaborating
Learn more about TechXchange Dev Days virtual and in-person events here
Share on LinkedIn
In this blog post, we'll explore how you can use IBM Cloud Code Engine to run binaries inside the existing Node.js and Python runtimes.
IBM Cloud Code Engine is IBMs Strategic serverless compute platform that supports a variety of workloads including functions. A function is a stateless code snippet, that perform tasks as it is invoked by HTTP. For Functions, Code Engine currently supports two programming languages: Node.js and Python. But what if you prefer to use a different language?
The solution lies in utilizing one of the existing runtimes, which is provided by IBM Cloud Code Engine. and bundling and executing a binary. In this example, we'll create a simple function using the Python runtime which will run (subprocess.run), a binary written in Go. We'll leverage the ability to add the binary to the function's code bundle during the build process.
subprocess.run
__main__.py
import subprocess import json output_dict={} statusCode = 0 binary="my-program" def main(params): command = f'./{binary} \'{json.dumps(params)}\'' result = subprocess.run(command, shell=True, capture_output=True, text=True) if result.returncode == 0: statusCode = 200 output_dict = json.loads(result.stdout) else: statusCode = 500 output_dict = {"error":"an error as occured"} return { "headers": { 'Content-Type': 'application/json; charset=utf-8', }, "statusCode": statusCode, "body": output_dict, }
main.go
package main import ( "encoding/json" "fmt" "os" ) type Response struct { Key string `json:"key"` Value string `json:"value"` Data interface{} `json:"data"` } func main() { // recive data as json string and unmarshal into variable var inputData map[string]interface{} if len(os.Args) > 1 { jsonString := os.Args[1] err := json.Unmarshal([]byte(jsonString), &inputData) if err != nil { os.Exit(1) } } // Here comes your logic name := "placeholder" if len(inputData) != 0 { name = inputData["name"].(string) } // return the response json (to the python code) respones := Response{ Key: "New Key", Value: name, Data: inputData, } responseJSON, err := json.Marshal(respones) if err != nil { os.Exit(1) } fmt.Println(string(responseJSON)) }
.ceignore
linux/amd64
GOOS=linux GOARCH=amd64 go build -o "my-program" -ldflags="-s -w" ./main.go
├── __main__.py ├── main.go ├── .ceignore └── my-program
ibmcloud ce fn create --name <function-name> --runtime python-3.11 --build-source .
And that’s it! You have now successfully created a IBM Code Engine Function by deploying your Python wrapper code and your Go binary and executed it on the IBM Cloud.