-
Notifications
You must be signed in to change notification settings - Fork 8
Google Cloud Functions
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.
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.
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.
Cloud Function disediakan dalam Node.js, Python, and Go. Untuk Java sampai tulisan ini dibuat masih status Alpha. Namun untuk custom function bisa gunakan Java Library.Salah satu implementasi Cloud Function di projeck ini adalah untuk merespon Docker Webhook.
Lihat HTTP Tutorial dan HTTP Functions:
$ gcloud functions deploy FUNCTION_NAME --runtime nodejs8 --trigger-http
$ gcloud functions call FUNCTION_NAME --data '{"name":"Keyboard Cat"}'
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"}'
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))
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"
}
}
Hello World!
'name'
di Source dengan 'callback_url' maka respon dari request ini:
Hello https://registry.hub.docker.com/u/svendowideit/testhook/hook/2141b5bi5i5b02bec211i4eeih0242eg11000a/!
Hello testhook!
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"
}
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))
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 filerequirements.txt
sbb:
# Function dependencies, for example:
# package>=version
-i https://pypi.python.org/simple
requests>=2.22.0
Selanjutnya kita akan integrasikan dengan triggering ke pipeline di Codefresh.
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"}}'
from flask import escape
import requests
import json
import os
def http_callback(event):
"""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": "image PASSED",
"context": "Continuous integration by Codefresh",
"target_url": "https://g.codefresh.io/api/builds/5b1a78d1bdbf074c8a9b3458"
}
event_json = event.get_json(silent=True)
if event_json and 'callback_url' in event_json:
callback_url = event_json['callback_url']
r = requests.post(url=callback_url, data=payload, headers=headers)
return http_trigger(event_json)
def http_trigger(event_json):
"""HTTP Cloud Function.
Args:
Requests is an elegant and simple HTTP library for Python, built for human beings..
<https://requests.readthedocs.io/en/latest/#requests-http-for-humans>
Returns:
Example - Triggering pipelines
You can also pass extra environment variables using an array
<https://codefresh.io/docs/docs/integrations/codefresh-api/#example---triggering-pipelines>.
"""
headers = {
"content-type": "application/json; charset=utf-8",
"Authorization": "{}".format(escape(os.environ.get("CF_API_KEY")))
}
payload = {
"serviceId": os.environ.get("CF_SERVICE_ID"),
"variables": {"JSON_DATA": json.dumps(event_json)}
}
url = "https://g.codefresh.io/api/builds/" + os.environ.get("CF_SERVICE_ID")
r = requests.post(url, data=json.dumps(payload), headers=headers)
return str(r.status_code)
Contoh di atas bisa dilakukan untuk banyak kepentingan lain. Pustaka program bantu seperti Request secara default sudah termasuk dalam file Pipfile sehingga akan selalu tersedia dalam pengoperasian secara keseluruhan via requirements.txt dan requirements_dev.txt.
Untuk skala yang lebih tinggi dimana diperlukan lingkungan yang menunjang kluster tanpa perlu menyediakan server maka Anda bisa pakai Cloud Run. Memungkinkan Anda untuk menjalankan kontainer stateless di lingkungan yang dikelola sepenuhnya atau di cluster GKE Anda sendiri.
This documentation is mapped under Mapping and licensed under Apache License, Version 2.0.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright (c) 2018-2020 Chetabahana Project
You are on the wiki of our repo
- Site
- Main
- Project
- Pratinjau
- Pola Dasar
- Bagan Kerja
- Field Tutorial
- Cloud Site API
- Google Ads API
- Cloud Tasks API
- Google Trends API
- Basis Implementasi
- Beranda
- Perangkat
- Pasang Aplikasi
- Penyetelan Aplikasi
- Menyiapkan Frontend
- Menjalankan Backend API
- Menjalankan Toko