1. 程式人生 > >Quick lab: No infrastructure, just code. See the simplicity of serverless

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 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 b not more, not less b 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. IBM Cloud Functions also inlucdes 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.

Learning objectives

This tutorial walks you through the steps required to create, build, and run a serverless application using IBM Cloud Functions.

Prerequisites

  • An account with IBM Cloud. You can use your existing account or create a new account

Estimated time

Completing this tutorial should take about 45 minutes.

Steps

1. Create an IBM Cloud account

If you have an existing IBM Cloud account, skip to the next section.

  1. For the steps in this tutorial, you need to create a free trial account on IBM Cloud. The instructions in this tutorial do not incur any additional costs.
  2. Create an IBM Cloud Trial account at https://console.bluemix.net, and click on Create a Free Account.
  3. Complete the registration form with your details and a valid email address.
  4. Click Create Account.
  5. Confirm your registration by accessing your email and clicking Confirm Account.
  6. Now you can log in.
  7. Click Login and enter your email and password.
  8. You see the Dashboard, which is emptly because you have not created any services or apps at this point.

    Note the Region, Cloud Foundry Org and Cloud Foundry Space settings. Typically the settings are US South, the same as your email address, and, by default, you are placed in a space called dev, as shown in the following screen capture.

2. Create an action

There are two main options to get started with Cloud Functions. 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. Click the Navigation menu in the header:

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

  2. The menu on the left side contains the following sections:

    a. The Actions section lists all actions you previously created. Clicking an action loads its code into the code editor. Hovering over an action gives you the option to click a trash icon to delete the action.

    b. the Triggers section lists all the triggers you previously created. Hover over a trigger to view a flash icon, which you can use to fire the trigger, and a trash icon, which you can use to delete the trigger.

    c. The Monitor section displays information about your actions and their activity, including an activity summary and timeline.

    d. The Logs section open the Logging service, which you can use to collect, analyze, and build dashboards for your logs.

  3. Create your first action by clicking Start Creating. On the Create page, select the Create Action option:

  4. Enter an action name, for example, hello, and select Node.js 6 for the runtime environment. Leave everything else as is and click Create.

  5. In the cloud-based code editor that opens, you can create and extend your actions. Copy the following code snippet into the code editor, replacing any existing code:

    function main() {
    return { message: "Hello world" };
    }
    
  6. Click Save. The Save button is replaced with an Invoke button. Click Invoke to test your action directly from your browser. You should see the following result directly in your browser:

    {
      "message": "Hello world"
    }
    

  7. You can invoke actions with several named parameters. To see what happens when working with an action that accepts parameters, update the action code to the following example:

    function main(msg) {
      return { message: "Hello, " + msg.name + " from " + msg.place };
    }
    

    Click Save.

  8. This action now requires some input parameters. Add the parameters before invoking the action. Click Change Input:

    Then add the following example JSON data in the Change Action Input box:

    {
      "name": "Andreas",
      "place": "Stuttgart, Germany"
    }
    

    Click Apply.

  9. You can now run the action with the new input data by clicking Invoke. You should receive the following result:

    {
      "message": "Hello, Andreas from Stuttgart, Germany"
    }
    

3. Create a trigger

Cloud Functions is a Function-as-a-Service (FaaS) platform that runs code in response to events. Events are emitted in one of two ways:

* Events can be emitted by services, like other services that are part of the IBM Cloud platform. These services have triggers that represent a named channel for a stream of events.

* Events can be emitted in the form of API calls, fired by standard web or mobile applications, which can then trigger actions.

So far, you have only triggered actions manually. Now, try triggering actions another way: periodically.

  1. Update your existing action to contain the following sample code:

    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)." };
    }
    

    and click Save.

    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. Next, click Connected Triggers to add a Trigger that causes the action to be run.

    Then, click Add Trigger and select a Periodic trigger:

    Give your trigger a name (for example, minute alarm), scroll down to UTC Minutes, and select Every Minute from the list.

    Click Create & Connect to create the trigger and connect your action to it. Click <- Actions to return to the dashboard.

    Select Monitor from the menu to see the activity of your actions and triggers. The Activity Log should show your triggered action and the time it was triggered, as shown in the following screen capture:

    To delete the trigger, expand the Triggers section, select the Minute Alarm trigger that you just created, and select the option to delete it, as shown in the following screen capture:

4. Create a web action.

  1. Select Actions from the menu on the left side. Then, select your hello action and select the Manage Action option from the list:

    Change the code in the action back to the Hello action that takes name and place parameters:

     var counter = 0; // global variable
     function main(msg) {
         return { message: "Hello, " + msg.name + " from " + msg.place };
     }
    

    Click Save.

  2. To add a web endpoint and create a web action, click Endpoints on the menu on the left, and then select Enable as a Web Action and click Save. After it is saved, you can use the clipboard icon to copy the URL to the clipboard:

  3. Paste the copied URL into the browser window, appending the following query parameters to the request:

    ?name=Andreas&place=Stuttgart
    

    This step passes the name and place input parameters into the action. You should then get the output of your action as a response:

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 a cloud-native serverless app written in Node.