Google Cloud Functions

An example integration where a Data Connector forwards events to a Google Cloud Function.

Overview

This example uses a Data Connector to forward the events of all devices in a project to a Google Cloud Function. When receiving the HTTPS POST request, our function will verify both the origin and content of the request using a Signature Secret, then decode the data.

Prerequisites

The following points are assumed.

Google Cloud Platform

While there are many advantages to using a local environment for development, this guide will solely focus on using the browser portal to minimize setup requirements.

Create a Cloud Function

Following this guide, create a new Cloud Function with the following configurations.

Python 3.9
Python API (Beta)
Node.js 14
Go 1.13
Python 3.9

(1) Configuration

Trigger

  • Trigger Type: HTTP

  • Authentication: Allow unauthenticated invocations.

Variables, Networking and Advanced Settings

Add a new runtime environment variable with the following values.

  • Name: DT_SIGNATURE_SECRET

  • Value: Some unique password which we will use later. Write it down.

(2) Code

  • Runtime: Python 3.9

  • Entry point: dataconnector_endpoint

In the Source Code, edit main.py with the following snippet. The implementation is explained in detail on the Data Connector Advanced Configurations page.

main.py
import os
import hashlib
import jwt
# Fetch environment variables.
SIGNATURE_SECRET = os.environ.get('DT_SIGNATURE_SECRET')
def verify_request(body, token):
# Decode the token using signature secret.
try:
payload = jwt.decode(token, SIGNATURE_SECRET, algorithms=["HS256"])
except Exception as err:
print(err)
return False
# Verify the request body checksum.
m = hashlib.sha1()
m.update(body)
checksum = m.digest().hex()
if payload["checksum"] != checksum:
print('Checksum Mismatch')
return False
return True
def dataconnector_endpoint(request):
# Extract necessary request information.
body = request.get_data()
token = request.headers['x-dt-signature']
# Validate request origin and content integrity.
if not verify_request(body, token):
return ('Could not verify request.', 400)
#
# Further processing here.
#
return ('OK', 200)

Append the following snippet to requirements.txt.

requirements.txt
pyjwt==2.1.0
Python API (Beta)

For details, read our Python API Documentation.

(1) Configuration

Trigger

  • Trigger Type: HTTP

  • Authentication: Allow unauthenticated invocations.

Variables, Networking and Advanced Settings

Add a new runtime environment variable with the following values.

  • Name: DT_SIGNATURE_SECRET

  • Value: Some unique password which we will use later. Write it down.

(2) Code

  • Runtime: Python 3.9

  • Entry point: dataconnector_endpoint

In the Source Code, edit main.py with the following snippet.

main.py
import os
from dtintegrations import data_connector, provider
DT_SIGNATURE_SECRET = os.getenv('DT_SIGNATURE_SECRET')
def dataconnector_endpoint(request):
# Validate and decode the incoming request.
event = data_connector.http_push.decode_request(
request,
provider=provider.GCLOUD,
secret=DT_SIGNATURE_SECRET,
)
# Print the event data.
print(event)
# If all is well, return 200 response.
return ('OK', 200)

Append the following snippet to requirements.txt.

requirements.txt
dtintegrations
Node.js 14

(1) Configuration

Trigger

  • Trigger Type: HTTP

  • Authentication: Allow unauthenticated invocations.

Variables, Networking and Advanced Settings

Add a new runtime environment variable with the following values.

  • Name: DT_SIGNATURE_SECRET

  • Value: Some unique password which we will use later. Write it down.

(2) Code

  • Runtime: Node.js 14

  • Entry point: dataconnectorEndpoint

In the Source Code, edit index.js with the following snippet. The implementation is explained in detail on the Data Connector Advanced Configurations page.

index.js
const crypto = require('crypto')
const jwt = require('jsonwebtoken') // npm install [email protected]
// Fetch environment variables.
const signatureSecret = process.env.DT_SIGNATURE_SECRET
function verifyRequest(body, token) {
// Decode the token using signature secret.
let decoded;
try {
decoded = jwt.verify(token, signatureSecret)
} catch(err) {
console.log(err)
return false
}
// Verify the request body checksum.
let shasum = crypto.createHash('sha1')
let checksum = shasum.update(JSON.stringify(body)).digest('hex')
if (checksum !== decoded.checksum) {
console.log('Checksum Mismatch')
return false
}
return true
}
exports.dataconnectorEndpoint = (req, res) => {
// Extract necessary request information.
let body = req.body
let token = req.get('X-Dt-signature')
// Validate request origin and content integrity.
if (verifyRequest(body, token) === false) {
res.sendStatus(400);
return
}
//
// Further processing here.
//
res.sendStatus(200);
};

Edit package.json to contain the following dependencies field.

package.json
{
"dependencies": {
"jsonwebtoken": "^8.5.1"
}
}
Go 1.13

(1) Configuration

Trigger

  • Trigger Type: HTTP

  • Authentication: Allow unauthenticated invocations.

Variables, Networking and Advanced Settings

Add a new runtime environment variable with the following values.

  • Name: DT_SIGNATURE_SECRET

  • Value: Some unique password which we will use later. Write it down.

(2) Code

  • Runtime: Go 1.13

  • Entry point: DataconnectorEndpoint

In the Source Code, edit function.go with the following snippet. The implementation is explained in detail on the Data Connector Advanced Configurations page.

function.go
package triggerfunction
import (
"crypto/sha1"
"encoding/hex"
"fmt"
jwt "github.com/dgrijalva/jwt-go" // go get github.com/dgrijalva/[email protected]
"io/ioutil"
"log"
"net/http"
"os"
)
// Environment variables.
var signatureSecret = os.Getenv("DT_SIGNATURE_SECRET")
// verifyRequest validates the request origin and content integrity.
func verifyRequest(bodyBytes []byte, tokenString string) error {
// Decode the token using signature secret.
claims := jwt.MapClaims{}
_, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(signatureSecret), nil
})
if err != nil {
return err
}
// Verify the request body checksum.
sha1Bytes := sha1.Sum(bodyBytes)
sha1String := hex.EncodeToString(sha1Bytes[:])
if sha1String != claims["checksum"] {
return fmt.Errorf("Checksum mismatch.")
}
return nil
}
// DataConnectorEndpoint receives, validates, and returns a response for the forwarded event.
func DataconnectorEndpoint(w http.ResponseWriter, r *http.Request) {
// Extract necessary request information.
tokenString := r.Header.Get("x-dt-signature")
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
// Validate request origin and content integrity.
if err := verifyRequest(bodyBytes, tokenString); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
//
// Further processing here.
//
log.Println("OK")
fmt.Fprintf(w, "OK\n")
}

Replace the content of go.mod with the following snippet.

module example.com/cloudfunction
go 1.13
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
)

When configured, deploy your function.

Post Deployment

Your function is now ready to receive requests, but we need to know to which URL to send them. In your function, locate the TRIGGER tab and copy the Trigger URL. Save this for later.

Create a Data Connector

To continuously forward the data to our newly created Cloud Function, a Data Connector with almost all default settings is sufficient. If you are unfamiliar with how Data Connectors can be created, refer to our Creating a Data Connector guide. The following configurations should be set.

  • Endpoint URL: The Trigger URL found in the previous step.

  • Signature Secret: The value of DT_SIGNATURE_SECRET environment variable.

Depending on your integration it can also be smart to disable the event types you are not interested in. For instance, the NetworkStatusEvent is sent every Periodic Heartbeat and will by default be forwarded by the Data Connector if not explicitly unticked.

Test the Integration

If the integration was correctly implemented, the Success counter for your Data Connector should increment for each new event forwarded. This happens each Periodic Heartbeat or by touching a sensor to force a new event.

If instead the Error counter increments, a response containing a non-2xx status code is returned.

  • Verify that the Data Connector endpoint URL is correct.

  • Google provides a host of tools that can be used to monitor Cloud Functions. Check the logs for any tracebacks that could explain why an error is returned.

Next steps

Your sensor data is now in the Google Cloud environment and you can start using it in their various services. Fortunately, Google has some well-documented guides to get you started.

PostgreSQL Database

A database should be tailored to each specific use-case. However, if you're uncertain, PostgreSQL (Postgres) is a good place to get started. The following guides will show you how to create a new Postgres database, then connect your Cloud Function to execute queries.

DataStudio

Once your Database has been set up, the following guide shows you how to connect it to DataStudio for continuous data visualization and analytics.