Getting Started with Apache OpenWhisk
An open source serverless platform from IBM, OpenWhisk is available in two modes, hosted and on-premises. Developers can easily get started with it for implementing event-driven, loosely coupled functions.
Apache OpenWhisk’s architecture reflects a modern, containerized, distributed system. It’s fascinating to see how multiple technologies are utilized in designing this first open source serverless platform.
OpenWhisk is integrated with Bluemix, IBM’s Cloud Foundry-based PaaS and is also available as an open source software that can be deployed behind the firewall. Adobe and IBM jointly submitted OpenWhisk to Apache, which has now become an incubation project. It is one of the first open source serverless platforms in the market. In December 2016, IBM announced the general availability of Cloud Functions, the hosted version in the public cloud.
OpenWhisk Concepts and Terminology
Like other serverless frameworks, OpenWhisk invokes code snippets when a specific event occurs. There are three key concepts in OpenWhisk: Triggers, Rules, and Actions.
Triggers are associated with specific events such as adding a new row to a table, a commit in GitHub, a sensor reading exceeding a specific threshold. The Trigger is fired by the event source when a specific condition is met.
Actions is where the rubber meets the road. They are the code snippets that developers write that get invoked directly through an HTTP call or by a trigger. OpenWhisk supports JavaScript, Java, Swift, and even arbitrary binaries packaged as Docker containers.
Rules associate Actions with Triggers. They act as the glue binding the code snippets with event sources. One Rule can associate multiple Triggers with an Action.
Additionally, deployments can be streamlined through packages and feeds. A package is a bundled collection of related code snippets that can be easily shared with others. Feeds make it easy to integrate actions with event sources. It is also possible to chain multiple Actions into a sequence, which can be associated with a Trigger.
The simplest way to understand OpenWhisk is to think of it as a Pub/Sub infrastructure with the ability to embed and invoke code within the subscriber. Triggers can be compared to publishers while Actions are like subscribers. Rules play the role of a topic that associate subscribers and publishers.
All the entities of OpenWhisk including Triggers, Rules, and Actions can be created and invoked through the REST API. For example an event source can call the REST endpoint to initiate a Trigger which in turn invokes the corresponding Actions. This model makes it easy to implement a loosely coupled eventing system connecting various event sources with code snippets at runtime.
Getting Started
The easiest way to get started with OpenWhisk is to sign up with IBM Bluemix. You can create your first action using the browser-based code editor provided by Bluemix.
Once the Action is in place, you can download the OpenWhisk CLI to your machine. Written in the Go language, the client CLI is available for Linux, Mac, and Windows.
Like the Cloud Foundry CLI, OpenWhisk’s wsk tool needs to be configured for a specific API endpoint. For each Bluemix account, there will be a unique authentication key that can be passed to the wsk tool.
We can configure the CLI with the following command
bx wsk property set --apihost openwhisk.ng.bluemix.net --auth <unique_token>
Creating an Action to Send an Email
This tutorial will demonstrate how to use custom node.js packages to build a function, and invoking it asynchronously. You can get the source code for this tutorial from Github.
Since we use SendGrid for sending the email, we need to register and get an API key. After you sign in with your credentials, navigate to the Settings section and click on API Keys. Ensure that you save the API Key when it is displayed. It is shown only the first time it is created.
On your Mac, create a folder and run npm init command in it accepting the default values:
$ mkdir mailfunc $ cd mailfunc $ npm init
We will then install the npm for SendGrid that we need in our function.
$ npm install sendgrid -save
Let’s go ahead and create the function. Open your favorite editor and paste the code snippet.
function main(params) {
return new Promise(function(resolve, reject) {
if (!params.from || !params.to || !params.subject || !params.content) {
reject("Insufficient number of parameters");
}
var helper = require('sendgrid').mail
var sg = require('sendgrid')("YOUR_SENDGRID_API_KEY");
from_email = new helper.Email(params.from)
to_email = new helper.Email(params.to)
subject = params.subject
content = new helper.Content("text/plain", params.content)
mail = new helper.Mail(from_email, subject, to_email, content)
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON()
});
sg.API(request, function(error, response) {
if (error) {
reject(error);
} else {
console.log(response.statusCode)
console.log(response.body)
console.log(response.headers)
resolve({
msg: "Message sent!"
});
}
})
});
}
exports.main = main;
The function accepts various parameters that are required to send an email. We will pass those parameters from a Trigger when we invoke the Action.
It’s time for us to package and deploy the function. The following commands will compress all the dependencies into a zip file and deploys them to OpenWhisk:
$ zip -r action.zip *
$ bx wsk -i action create sendmail --kind nodejs:6 action.zip
ok: created action sendmail
$ bx wsk -i action list
actions
/guest/sendmail private nodejs:6
Invoking the Action
With the sendmail Action in place, let’s go ahead and invoke it. Start by creating a new folder.
$ mkdir ~/trigger
$ cd ~/trigger
Create a file called parameters.json which contains the parameters required to send an email. Replace the placeholders with appropriate values.
{
"from": "FROM_EMAIL_ADDRESS",
"to" : "TO_EMAIL_ADDRESS",
"subject" : "Alert from OpenWhisk",
"content" : "Hello Serverless"
}
We can now invoke the Action by passing the parameters file to the function:
$ bx wsk -i action invoke --blocking --result sendmail --param-file parameters.json
{
"msg": "Message sent!"
}
If you see the above output, it’s an indication that the function was successfully invoked. The recipient mentioned in the parameters.json will receive an email alert.
The –blocking switch forces synchronous invocation of the function. But when an external event source triggers it, the invocation must be asynchronous.
Let’s see how we can asynchronously invoke the same Action. For this, we simply omit the –blocking and –-result switches.
$ bx wsk -i action invoke sendmail --param-file parameters.json
ok: invoked /guest/sendmail with id 1671372a9f974b9080e24f3cc5081c2a
Notice that OpenWhisk has now returned an activation id, which can be used for tracking the status. We can also list all the activations associated with previous invocations. Even synchronously invoked functions will have an activation id.
$ wsk -i activation list
activations
1671372a9f974b9080e24f3cc5081c2a sendmail
690895452c6c4d719a8dc77301376165 sendmail
The activation with ID 1671372a9f974b9080e24f3cc5081c2a reflects the most recent one. Let’s see the outcome of that activation.
$ wsk -i activation result 1671372a9f974b9080e24f3cc5081c2a
{
"msg": "Message sent!"
}
Finally, let’s invoke the same Action from cURL.
$ export TYPE='Content-Type: application/json'
$ export AUTH='Authorization: Basic '`wsk property get --auth | awk '{printf("%s", $3)}' | base64 `
export API_ENDPOINT=<API_ENDPOINT>
$ export NAMESPACE=<NAMESPACE>
$ curl -k -s -X POST -d '{"from": "FROM_EMAIL_ADDRESS", "to": "TO_EMAIL_ADDRESS","subject":"Alert from OpenWhisk","content":"Hello Serverless"}' -H "$TYPE" -H "$AUTH" https://$API_ENDPOINT
/api/v1/namespaces/$NAMESPACE/actions/sendmail?blocking=true
As you can see, this Action can now be triggered from any event source capable of talking to a REST endpoint. You can easily integrate this function with any application that needs to send a notification as an email.
Making Digital Transformation offerings with ServiceNow for client and partner success
7 年Did you try it on BlueMix ?
Enterprise Architect
7 年Good overview . Will be Interesting to compare with other serverless products like aws lambda and azure functions .
Always in for building culture of innovation and empowerment
7 年Cool stuff...need to look at it...Thanks!
Thought Leader, Fellow BCS, Distinguished Architect | Executive IT Architect @ IBM Cloud & AI | Speaker, Tech Blogger - DZone Core & MVB | Cryptography & Optimization, Math, Quantum & Data Science
7 年Thanks for an awesome overview and a cool demo sir.
30+ years of li(o)ving computers - DOS to SaaS! PC to Cloud! Cloud Architect - AWS CSAP!
7 年Thanks for the lovely introduction webinar and demo Jani! IOU again!