Digital Developer Conference on Cloud Native Security: Register for free and choose your sessions. June 24, 25, & July 1, 2020 Learn more

Quick lab: No infrastructure, just code. See the simplicity of serverless.

Serverless computing refers to a model where the existence of servers is entirely abstracted away. Even though servers exist, developers are relieved from the need to care about their operation. They are relieved from the need to worry about low-level infrastructural and operational details such as scalability, high-availability, infrastructure-security, and other details. Serverless computing is essentially about reducing maintenance efforts to allow developers to quickly focus on developing code that adds value.

Serverless computing simplifies developing cloud-native applications, especially microservice-oriented solutions that decompose complex applications into small and independent modules that can be easily exchanged.

Serverless computing does not refer to a specific technology. Instead, it refers to the concepts underlying the previously described model. Some promising solutions like Apache OpenWhisk have recently emerged that ease development approaches used in the serverless model.

IBM Cloud Functions (ICF) is a Function-as-a-Service (FaaS) platform on IBM Cloud, built using the Apache OpenWhisk open source project, that allows you to execute code in response to an event.

It provides a serverless deployment and operations model. With a granular pricing model that works at any scale, you get exactly the resources you need – not more, not less – and you are charged for code that is really running. The flexible programming model includes support for languages like JavaScript, Swift, Python, and Java and support for running custom logic through Docker containers. This programming model allows small agile teams to reuse existing skills and to develop in a fit-for-purpose fashion. ICF also includes tools to declaratively chain together the building blocks you develop. You can chain microservices to form workflows through composition. It is open and can run anywhere to avoid any kind of vendor lock-in.

Estimated time

Completing this tutorial should take about 45 minutes.

Prerequisites

To complete this tutorial, you will need an IBM Cloud account. If you don’t have an existing account, see the Signing up for IBM Cloud documentation for detailed instructions.

Steps

Here are the steps required to complete this tutorial.

  1. Create an action
  2. Invoke with parameters
  3. Create a trigger
  4. Create a web action

1. Create an action

There are two main options to get started with ICF. With both, you work with basic Cloud Functions entities by creating, updating, and deleting actions, triggers, rules, and sequences.

With the command line interface, you perform these basic operations from the shell. With the Cloud Functions user interface, you perform the same operations from your browser. This tutorial uses the browser user interface.

  1. Log in to IBM Cloud: https://cloud.ibm.com.

  2. Click the Navigation menu in the header:

    IBM Dashboard top menu

  3. Click Functions to access ICF, the cloud-native development experience on IBM Cloud.

    IBM Cloud service dropdown

  4. You should now be in the ICF web console. The page should have a left menu that provides navigation to all top-level features of ICF. In this tutorial, you will explore the following feature areas shown in the menu:

    • Actions, which are used to create, edit, and manage actions using any supported functional coding language.

    • Triggers, which are used to create, edit, and manage triggers that automate the running or firing of your actions using events.

    • Monitor, which is used to display information about your action and trigger invocations (like executions) on your account, including an activity summary and timeline.

  5. Create your first action by clicking the Start Creating button on the functions home page:

    ICF start creating menu

    Then click on Create Action:

    ICF create action page

  6. Enter an action name, such as hello, and verify that the runtime dropdown shows the latest default Node.js runtime version (for example, Node.js 10). Now click the Create button:

    ICF action create

  7. In the cloud-based code editor that opens, you can create and modify your action’s function. The editor should be pre-filled with a Hello World function written in Node.js:

     javascript
     function main(params) {
            return { message: "Hello World" };
        }
    

    Note: If you do not see the code snippet above, you can copy and paste it into the code editor replacing any existing code and click Save. You should then see the Invoke button for the next step.

  8. Click Invoke to test your action directly from your browser:

    ICF invoke button

    An Activations section should appear with an activation record caused by your invocation that includes an activation ID, invocation results, and any log entries the function writes (in our case none):

    ICF activation button

    Now you should see that the result of our invocation is a JSON object with our Hello World message:

     json
     {
       "message": "Hello World"
     }
    

    A unique activation record is logged for every invocation that contains detailed configuration and metric information not shown on this page. Later in this tutorial, you will explore the Monitor dashboard where you can view all account activations over time and access their details.

    Note: If you navigate away from this window and come back, the activations shown here will be reset.

2. Invoke with parameters

The user interface allows named parameters to be declared and passed to functions in JSON object format.

  1. Make sure your code window is in edit mode. Update the hello action function with the code below and click Save:

     javascript
     function main(params) {
        return { message: "Hello, " + params.name + " from " + params.place };
     }
    
  2. This action now requires the input parameters name and place. To add parameters, click Invoke with parameters:

    ICF parameters

    This will cause the Change Action Input dialog to appear.

  3. Add the following JSON data to the Change Action Input dialog’s input area and click Apply:

     json
     {
       "name": "Elrond",
       "place": "Rivendell"
     }
    

    ICF action input

  4. Run the action again using the new input data by clicking Invoke. You should receive the following result:

     json
     {
       "message": "Hello, Elrond from Rivendell"
     }
    

3. Create a trigger

As a FaaS platform, ICF runs code in response to events. Events can be generated by the following:

  • API calls fired by standard web or mobile applications, which can be configured to trigger actions. This is what you have been doing so far in the user interface; the invoke button triggered a direct call to your action.

  • Services that are either part of the IBM Cloud platform or external service providers using triggers.

In these next steps, you will create a trigger to periodically run a function using the ICF built-in Alarm service.

  1. Update your existing hello action with the following sample code and click Save:

     javascript
     var counter = 0; // global variable
     function main(msg) {
         var date = new Date();
         var time = date.getHours() + ":" + date.getMinutes() + ":" +
         date.getSeconds();        
         counter++;
         return { message: "It is " + time + ". This action has been called " + counter + " time(s)." };
     }
    

    This action returns the time and the frequency of times invoked. A counter is used as a global variable to maintain the count. Because it is a global variable, it persists across invocations of the same action.

  2. Click Connected Triggers on the left menu and then click Add Trigger:

    ICF connected triggers

    Now select a Periodic as your trigger type:

    ICF periodic triggers

  3. Give your trigger the name minute alarm. Then scroll down under Timer Settings to the UTC Minutes pattern, and select Every Minute from the dropdown. Click the Create & Connect button to create the trigger and connect it to the hello action:

    ICF periodic trigger configuration

  4. Use the breadcrumb in the top left to navigate to the Actions section and select Monitor from the left menu to see the recent activities of your actions and triggers.

    View recent action and trigger activity

    The Activity Log should show the periodic alarm feed indeed fired the minute alarm trigger every minute which in turn fired the connected hello action:

    ICF monoitor alarm

  5. Make sure you delete the trigger or it will continue to fire every minute, which is charged against your account tier’s compute usage!

    Click the trash can icon next to the `minute alarm“ to delete it, as shown here:

    Delete your trigger

    Select Delete on the confirmation dialog that appears.

    Note: Alternatively, you can disable the trigger by clicking on its name and unchecking the Enabled setting under the Connection column. You would then use the breadcrumb to navigate back to the Triggers page.

4. Create a web action

Now you will make your hello action web-accessible and have ICF automatically create an HTTP endpoint for it.

  1. Select Actions from the menu on the left side. Then, select your hello action:

    ICF Hello action

  2. Update your existing hello action with the following code:

    function main(params) {
        let html = '<html style="color:red"><body><p>' +
        'Hello, ' + params.name + ` from ` + params.place +         
        '</p></body></html>'
        return { headers: { "Content-Type": "text/html" },
                 body: html };
    }
    

    Now click Save:

    ICF web action created

    The function now returns a Hello World message formatted in HTML which is returned in the body of the HTTP response. Notice that we also set the proper Content-Type to text/html in the HTTP response header.

  3. To make your action a web action, click Endpoints on the left menu. Then check the box Enable as Web Action and click Save.

    ICF enabled web action

  4. After it is saved, you can open the generated URL in your web browser by clicking on it.

    ICF web action URL

    Now your greeting should appear:

    ICF web action output

    However, it shows undefined for the values of name and place. Let’s fix that.

  5. Append the following query parameters to the URL in the browser and resubmit the request:

     ?name=Frodo&place=Shire
    

    As you can see, the query parameters for name and place were passed as input parameters into the action:

    ICF web action output paramaters

Summary

Congratulations! You successfully built and deployed several serverless Cloud Functions, including web actions that can be invoked from the browser or from microservices – all from inside a browser.

Now you can try these steps with your own code. Experiment some more with running cloud-native serverless apps written in Node.js.

Matt Rutkowski
Chris Bailey
Carlos Santana