Skip to content

Google Cloud Functions

Chetabahana edited this page Aug 24, 2019 · 79 revisions

Table of Contents

Benefit

Fungsi cloud memungkinkan Anda untuk membuat respon online dengan intruksi program baik secara langsung ataupun via feedback dari suatu layanan tanpa harus menyediakan server.

Respon dapat dikirim ke sumber daya lain di Google Platform maupun tempat lain seperti GitHub Actions atau Codefresh untuk triggering atau akses database seperti vitess.

Harga

Fungsi Cloud diberi harga sesuai dengan berapa lama fungsi Anda berjalan, berapa kali itu dipanggil dan berapa banyak sumber daya yang Anda berikan untuk fungsi tersebut.

SSL/TLS

Fungsi yang digunakan dengan pemicu HTTP diberikan domain yang sepenuhnya memenuhi syarat bersama dengan sertifikat SSL / TLS yang dihasilkan secara dinamis untuk komunikasi yang aman.

Menggunakan Repositori Sumber Cloud Anda dapat menggunakan Fungsi Cloud langsung dari repositori GitHub atau Bitbucket Anda tanpa perlu mengunggah kode atau mengelola versi sendiri.

Implementasi

Salah satu implementasi Cloud Function di projeck ini adalah untuk merespon Docker Webhook.

Listener

Lihat HTTP Tutorial dan HTTP Functions:

$ gcloud functions deploy FUNCTION_NAME --runtime nodejs8 --trigger-http
$ gcloud functions call FUNCTION_NAME --data '{"name":"Keyboard Cat"}'

Trigger

Cara ackifkan via Http Post:

curl -X POST "https://YOUR_REGION-YOUR_PROJECT_ID.cloudfunctions.net/FUNCTION_NAME" -H "Content-Type:application/json" --data '{"name":"Keyboard Cat"}'
Anda dapat melakukan test di Console Cloud Function

Source

Contoh dalam python:

from flask import escape

def hello_http(request):
    """HTTP Cloud Function.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    request_json = request.get_json(silent=True)
    request_args = request.args

    if request_json and 'name' in request_json:
        name = request_json['name']
    elif request_args and 'name' in request_args:
        name = request_args['name']
    else:
        name = 'World'
    return 'Hello {}!'.format(escape(name))

Event

Contoh Docker Webhook Post format:

{
  "callback_url": "https://registry.hub.docker.com/u/svendowideit/testhook/hook/2141b5bi5i5b02bec211i4eeih0242eg11000a/",
  "push_data": {
    "images": [
        "27d47432a69bca5f2700e4dff7de0388ed65f9d3fb1ec645e2bc24c223dc1cc3",
        "51a9c7c1f8bb2fa19bcd09789a34e63f35abb80044bc10196e304f6634cc582c",
        "..."
    ],
    "pushed_at": 1.417566161e+09,
    "pusher": "trustedbuilder",
    "tag": "latest"
  },
  "repository": {
    "comment_count": 0,
    "date_created": 1.417494799e+09,
    "description": "",
    "dockerfile": "#\n# BUILD\u0009\u0009docker build -t svendowideit/apt-cacher .\n# RUN\u0009\u0009docker run -d -p 3142:3142 -name apt-cacher-run apt-cacher\n#\n# and then you can run containers with:\n# \u0009\u0009docker run -t -i -rm -e http_proxy http://192.168.1.2:3142/ debian bash\n#\nFROM\u0009\u0009ubuntu\n\n\nVOLUME\u0009\u0009[/var/cache/apt-cacher-ng]\nRUN\u0009\u0009apt-get update ; apt-get install -yq apt-cacher-ng\n\nEXPOSE \u0009\u00093142\nCMD\u0009\u0009chmod 777 /var/cache/apt-cacher-ng ; /etc/init.d/apt-cacher-ng start ; tail -f /var/log/apt-cacher-ng/*\n",
    "full_description": "Docker Hub based automated build from a GitHub repo",
    "is_official": false,
    "is_private": true,
    "is_trusted": true,
    "name": "testhook",
    "namespace": "svendowideit",
    "owner": "svendowideit",
    "repo_name": "svendowideit/testhook",
    "repo_url": "https://registry.hub.docker.com/u/svendowideit/testhook/",
    "star_count": 0,
    "status": "Active"
  }
}
Jika kita kirim request ini maka responnya:
Hello World!
Kita ubah 'name' di Source dengan 'callback_url' maka respon dari request ini:
Hello https://registry.hub.docker.com/u/svendowideit/testhook/hook/2141b5bi5i5b02bec211i4eeih0242eg11000a/!
Ubah lagi ['callback_url'] dengan ['repository']['name'] maka respon dari request ini:
Hello testhook!

Callback

Validate

Untuk memvalidasi panggilan balik dalam Docker webhook, Anda harus melakukan hal berikut:

  • Ambil nilai callback_url di payload JSON permintaan.
  • Kirim permintaan POST ke URL ini yang berisi badan JSON yang valid.
{
  "state": "success",
  "description": "387 tests PASSED",
  "context": "Continuous integration by Acme CI",
  "target_url": "http://ci.acme.com/results/afd339c1c3d27"
}

Respon

Dengan menggunakan python: requests ubah Source untuk respon seperti trigger curl sbb:

from flask import escape
import requests

def hello_http(request):
    """HTTP Cloud Function.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    headers = {}
    payload = {
      "state": "success",
      "description": "387 tests PASSED",
      "context": "Continuous integration by Acme CI",
      "target_url": "http://ci.acme.com/results/afd339c1c3d27"
    }
    request_args = request.args
    request_json = request.get_json(silent=True)

    if request_json and 'callback_url' in request_json:
        callback_url = request_json['callback_url']
    elif request_args and 'callback_url' in request_args:
        callback_url = request_args['callback_url']
    else:
        callback_url = 'World'
    res = requests.post(url=callback_url, data=payload, headers=headers)
    return 'Send the payload data to: {}!'.format(escape(callback_url))

Deploy

Untuk jalankan dengan Requests dapat diakukan salah satu dari cara berikut:

  • clone sumber dan masukkan respon dengan nama file main.yml disitu atau
  • cukup masukkan versinya saja di file lain dengan nama requirements.txt atau
  • masukkan respon ke file main.yml di console dan edit file requirements.txt sbb:
# Function dependencies, for example:
# package>=version
-i https://pypi.python.org/simple
requests>=2.22.0

Integrasi

Selanjutnya kita akan integrasikan dengan triggering ke pipeline di Codefresh.

API/CLI

curl 'https://g.codefresh.io/api/builds/5b1a78d1bdbf074c8a9b3458' \
--compressed -H 'content-type:application/json; charset=utf-8' \
-H 'Authorization: <your_key_here>' \
--data-binary '{"serviceId":"5b1a78d1bdbf074c8a9b3458",\
"type":"build","repoOwner":"kostis-codefresh",\
"branch":"master","repoName":"nestjs-example",\
"variables":{"sample-var1":"sample1","SAMPLE_VAR2":"SAMPLE2"}}'

Function

from flask import escape
import requests

def http_trigger(request):
    """HTTP Cloud Function.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    headers = {
      "content-type:application/json; charset=utf-8",
      "Authorization: your_key_here"
    }
    payload = {
      "serviceId":"5b1a78d1bdbf074c8a9b3458",
      "type":"build",
      "repoOwner":"kostis-codefresh",
      "branch":"master",
      "repoName":"nestjs-example",
      "variables":{"sample-var1":"sample1","SAMPLE_VAR2":"SAMPLE2"}
    }
    target_url = 'https://g.codefresh.io/api/builds/5b1a78d1bdbf074c8a9b3458'
    res = requests.post(url=target_url, data=payload, headers=headers)
    return 'Send with payload data to: {}!'.format(escape(target_url))

    
def http_callback(request):
    """HTTP Cloud Function.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    headers = {}
    payload = {
      "state": "success",
      "description": "387 tests PASSED",
      "context": "Continuous integration by Acme CI",
      "target_url": "https://g.codefresh.io/api/builds/5b1a78d1bdbf074c8a9b3458"
    }
    request_args = request.args
    request_json = request.get_json(silent=True)

    if request_json and 'callback_url' in request_json:
        callback_url = request_json['callback_url']
    elif request_args and 'callback_url' in request_args:
        callback_url = request_args['callback_url']
    else:
        callback_url = 'World'
    res = requests.post(url=callback_url, data=payload, headers=headers)
    return 'Send the payload data to: {}!'.format(escape(callback_url))

Referensi

Project Tutorial

You are on the wiki of our repo

Chetabahana Project

Clone this wiki locally