Faas (Function as a Service)

The function is the center of the universe with cloud computing.

functions-python

Chalice Framework on AWS Lambda

Another option for developing serverless applications on AWS is to use the chalice framework.

Create credentials.

$ mkdir ~/.aws
$ cat >> ~/.aws/config
[default]
aws_access_key_id=YOUR_ACCESS_KEY_HERE
aws_secret_access_key=YOUR_SECRET_ACCESS_KEY
region=YOUR_REGION (such as us-west-2, us-west-1, etc)

Next setup a project.

python3 -m venv ~/.hello && source ~/.hello/bin/activate
chalice new-project hello && hello

Inspect the app.py file.

from chalice import Chalice

app = Chalice(app_name='hello')


@app.route('/')
def index():
    return {'hello': 'world'}

Then run local

(.chalicedemo) ec2-user:~/environment/helloworld4000 $ chalice local
Serving on http://127.0.0.1:8000

It can also run timed lambdas.

from chalice import Chalice, Rate

app = Chalice(app_name="helloworld")

# Automatically runs every 5 minutes
@app.schedule(Rate(5, unit=Rate.MINUTES))
def periodic_task(event):
    return {"hello": "world"}

It can also run event driven lambdas.

from chalice import Chalice

app = Chalice(app_name="helloworld")

# Whenever an object is uploaded to 'mybucket'
# this lambda function will be invoked.

@app.on_s3_event(bucket='mybucket')
def handler(event):
    print("Object uploaded for bucket: %s, key: %s"
          % (event.bucket, event.key))

Serverless

Serverless Framework

Google Cloud Functions

Google Cloud Functions have much in common with AWS Lambda. They work by invoking a function in response to an event. You can view a screencast of this workflow here.

Screencast

Google Cloud Screencast!

Why would you use Cloud Functions on GCP? According the official docs the use cases include ETL, Webooks, APIs, Mobile Backends and IoT.

Screen Shot 2020-03-26 at 2 20 44 PM

The editor allows you add “packages” on the fly.

Screen Shot 2020-03-26 at 1 55 15 PM

import wikipedia

def hello_wikipedia(request):
    """Takes JSON Payload {"entity": "google"}
    """
    request_json = request.get_json()

    if request_json and 'entity' in request_json:
        entity = request_json['entity']
        print(entity)
        res = wikipedia.summary(entity, sentences=1)
        return res
    else:
        return f'No Payload'

One the Google Cloud Function is deployed it can be tested in the console.

Screen Shot 2020-03-26 at 2 05 52 PM

The logs can also be inspected. There is where print statements show up.

Screen Shot 2020-03-26 at 2 07 17 PM

Notice that the GCP Console can also invoke this same function. First, let’s describe it and make sure it is deployed.

gcloud functions describe function-2

Screen Shot 2020-03-26 at 2 14 58 PM

Next, we can invoke it from the terminal.

gcloud functions call function-2 --data '{"entity":"google"}'

The results are here.

Screen Shot 2020-03-26 at 2 16 14 PM

Now, let’s try a new company, this time Facebook.

gcloud functions call function-2 --data '{"entity":"facebook"}'

The output shows the following.

executionId: 6ttk1pjc1q14
result: Facebook is an American online social media and social networking service
  based in Menlo Park, California and a flagship service of the namesake company Facebook,
  Inc.

Can we go further and call an AI API? Yes, we can. First add this library to the requirements.txt

# Function dependencies, for example:
# package>=version
google-cloud-translate
wikipedia

Next run this function.

import wikipedia

from google.cloud import translate

def sample_translate_text(text="YOUR_TEXT_TO_TRANSLATE", project_id="YOUR_PROJECT_ID"):
    """Translating Text."""

    client = translate.TranslationServiceClient()

    parent = client.location_path(project_id, "global")

    # Detail on supported types can be found here:
    # https://cloud.google.com/translate/docs/supported-formats
    response = client.translate_text(
        parent=parent,
        contents=[text],
        mime_type="text/plain",  # mime types: text/plain, text/html
        source_language_code="en-US",
        target_language_code="fr",
    )
    # Display the translation for each input text provided
    for translation in response.translations:
        print(u"Translated text: {}".format(translation.translated_text))
    return u"Translated text: {}".format(translation.translated_text)

def translate_test(request):
    """Takes JSON Payload {"entity": "google"}
    """
    request_json = request.get_json()

    if request_json and 'entity' in request_json:
        entity = request_json['entity']
        print(entity)
        res = wikipedia.summary(entity, sentences=1)
        trans=sample_translate_text(text=res, project_id="cloudai-194723")
        return trans
    else:
        return f'No Payload'

Screen Shot 2020-03-26 at 3 05 52 PM

Can you expand this even further to accept a payload that allows any language from the list of languages gcp supports here? Here is a gist of this code.

import wikipedia

from google.cloud import translate

def sample_translate_text(text="YOUR_TEXT_TO_TRANSLATE", 
    project_id="YOUR_PROJECT_ID", language="fr"):
    """Translating Text."""

    client = translate.TranslationServiceClient()

    parent = client.location_path(project_id, "global")

    # Detail on supported types can be found here:
    # https://cloud.google.com/translate/docs/supported-formats
    response = client.translate_text(
        parent=parent,
        contents=[text],
        mime_type="text/plain",  # mime types: text/plain, text/html
        source_language_code="en-US",
        target_language_code=language,
    )
    # Display the translation for each input text provided
    for translation in response.translations:
        print(u"Translated text: {}".format(translation.translated_text))
    return u"Translated text: {}".format(translation.translated_text)

def translate_test(request):
    """Takes JSON Payload {"entity": "google"}
    """
    request_json = request.get_json()
    print(f"This is my payload {request_json}")
    if request_json and 'entity' in request_json:
        entity = request_json['entity']
        language = request_json['language']
        print(f"This is the entity {entity}")
        print(f"This is the language {language}")
        res = wikipedia.summary(entity, sentences=1)
        trans=sample_translate_text(text=res, 
            project_id="cloudai-194723", language=language)
        return trans
    else:
        return f'No Payload'

The main takeaway in this change is grabbing another value from the request_json payload. In this case language. To test it the trigger accepts a new payload with the language added.

{"entity": "google", "language": "af"}

Screen Shot 2020-03-28 at 1 12 11 PM

Another item to mention is that you also may want to use the curl command to test out your cloud function. Here is an example of a curl command that you could tweak.

curl --header "Content-Type: application/json"   --request POST   --data '{"entity":"google"}' https://us-central1-<yourproject>.
cloudfunctions.net/<yourfunction>

Reference GCP Qwiklabs

Kubernetes FaaS with GKE