Рубрики
Uncategorized

Создать без серверных функций с OpenFAAS

OpenFAAS — это Framework function Forces, которая работает сверху Docker и Kubernetes. В этой Тьютории … с меткой без сервера, Kubernetes, Docker, DevOps.

OpenFAAS — это Framework function Forces, которая работает сверху Docker и Kubernetes. В этом руководстве вы узнаете, как:

  • Разверните OpenFAAS в кластер Kubernetes
  • Установите CLI OpenFAAS
  • Создание, сборка и развертывание функций без сервеса с помощью CLI
  • Вызвать функции без сервеса с помощью CLI
  • Обновить существующую функцию без сервера
  • Развернуть функции без серверов с помощью веб -интерфейса
  • Следите за своими функциями без сервера с помощью Prometheus и Grafana
  • Кластер Kubernetes Отказ Если у вас нет запущенного кластера Kubernetes, следуйте инструкциям из Установите кластер Kubernetes с добрым Раздел ниже.
  • Учетная запись Docker Hub Отказ Смотрите Docker Hub Страница для получения подробной информации о создании новой учетной записи.
  • kubectl Отказ Ссылка Установить и настроить kubectl Страница для получения подробной информации об установке kubectl.
  • Node.js 10 или выше. Чтобы проверить, установлен ли Node.js на вашем компьютере, введите следующую команду:
ode --version

В следующем примере вывод показывает, что Node.js установлен на вашем компьютере:

v10.16.3

Если Node.js не установлен или вы запускаете старую версию, вы можете скачать установщик из Загрузки страница.

  • Этот учебник предполагает базовое знакомство с Docker и Kubernetes.

С родом вы можете запустить локальную кластер Kubernetes, используя Docker Contaners в качестве узлов. Шаги в этом разделе Необязательно Отказ Следуйте за ними, только если вы У вас нет бега Kubernetes Cluster Отказ

1. Создайте файл с именем openfaas cluster.yaml и скопируйте в следующем спецификации:

# three node (two workers) cluster config
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
- role: worker

2. Используйте Дена создайте кластер Команда для создания кластера Kubernetes с одной плоскостью управления и двумя рабочими узлами:

kind create cluster --config kind-specs/kind-cluster.yaml
Creating cluster "kind" ...
 ✓ Ensuring node image (kindest/node:v1.17.0) 🖼
 ✓ Preparing nodes 📦 📦 📦
 ✓ Writing configuration 📜
 ✓ Starting control-plane 🕹️
 ✓ Installing CNI 🔌
 ✓ Installing StorageClass 💾
 ✓ Joining worker nodes 🚜
Set kubectl context to "kind-kind"
You can now use your cluster with:

kubectl cluster-info --context kind-kind

Thanks for using kind! 😊

Вы можете установить OpenFAAS, используя HELM, простые файлы YAML или его собственный установщик с именем Arkade который обеспечивает быстрый и простой способ работы OpenFAAS. В этом разделе вы развертываете OpenFAAS с Arkade Отказ

1. Введите следующую команду для установки Аркаде :

curl -sLS https://dl.get-arkade.dev | sudo sh
Downloading package https://github.com/alexellis/arkade/releases/download/0.1.10/arkade-darwin as /Users/andrei/Desktop/openFaaS/faas-hello-world/arkade-darwin
Download complete.

Running with sufficient permissions to attempt to move arkade to /usr/local/bin
New version of arkade installed to /usr/local/bin
Creating alias 'ark' for 'arkade'.
            _             _
  __ _ _ __| | ____ _  __| | ___
 / _` | '__| |/ / _` |/ _` |/ _ \
| (_| | |  |   < (_| | (_| |  __/
 \__,_|_|  |_|\_\__,_|\__,_|\___|

Get Kubernetes apps the easy way

Version: 0.1.10
Git Commit: cf96105d37ed97ed644ab56c0660f0d8f4635996

2. Теперь установить openfaas с:

arkade install openfaas
Using kubeconfig: /Users/andrei/.kube/config
Using helm3
Node architecture: "amd64"
Client: "x86_64", "Darwin"
2020/03/10 16:20:40 User dir established as: /Users/andrei/.arkade/
https://get.helm.sh/helm-v3.1.1-darwin-amd64.tar.gz
/Users/andrei/.arkade/bin/helm3/darwin-amd64 darwin-amd64/
/Users/andrei/.arkade/bin/helm3/README.md darwin-amd64/README.md
/Users/andrei/.arkade/bin/helm3/LICENSE darwin-amd64/LICENSE
/Users/andrei/.arkade/bin/helm3/helm darwin-amd64/helm
2020/03/10 16:20:43 extracted tarball into /Users/andrei/.arkade/bin/helm3: 3 files, 0 dirs (1.633976582s)
"openfaas" has been added to your repositories
Hang tight while we grab the latest from your chart repositories...
...Successfully got an update from the "ibm-charts" chart repository
...Successfully got an update from the "openfaas" chart repository
...Successfully got an update from the "stable" chart repository
...Successfully got an update from the "bitnami" chart repository
Update Complete. ⎈ Happy Helming!⎈
VALUES values.yaml
Command: /Users/andrei/.arkade/bin/helm3/helm [upgrade --install openfaas openfaas/openfaas --namespace openfaas --values /var/folders/nz/2gtkncgx56sgrpqvr40qhhrw0000gn/T/charts/openfaas/values.yaml --set gateway.directFunctions=true --set faasnetes.imagePullPolicy=Always --set gateway.replicas=1 --set queueWorker.replicas=1 --set clusterRole=false --set operator.create=false --set openfaasImagePullPolicy=IfNotPresent --set basicAuthPlugin.replicas=1 --set basic_auth=true --set serviceType=NodePort]
Release "openfaas" does not exist. Installing it now.
NAME: openfaas
LAST DEPLOYED: Tue Mar 10 16:21:03 2020
NAMESPACE: openfaas
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
To verify that openfaas has started, run:

  kubectl -n openfaas get deployments -l "release=openfaas, app=openfaas"
=======================================================================
= OpenFaaS has been installed.                                        =
=======================================================================

# Get the faas-cli
curl -SLsf https://cli.openfaas.com | sudo sh

# Forward the gateway to your machine
kubectl rollout status -n openfaas deploy/gateway
kubectl port-forward -n openfaas svc/gateway 8080:8080 &

# If basic auth is enabled, you can now log into your gateway:
PASSWORD=$(kubectl get secret -n openfaas basic-auth -o jsonpath="{.data.basic-auth-password}" | base64 --decode; echo)
echo -n $PASSWORD | faas-cli login --username admin --password-stdin

faas-cli store deploy figlet
faas-cli list

# For Raspberry Pi
faas-cli store list \
 --platform armhf

faas-cli store deploy figlet \
 --platform armhf

# Find out more at:
# https://github.com/openfaas/faas

Thanks for using arkade!

3. Убедитесь, что развертывания были созданы, запустите kubectl Получите развертывание командование Укажите пространство имен и селектор, используя -n и -l параметры следующим образом:

kubectl get deployments -n openfaas -l "release=openfaas, app=openfaas"

Если развертывания еще не готовы, вы должны увидеть что -то похожее на следующий пример вывода:

NAME                READY   UP-TO-DATE   AVAILABLE   AGE
alertmanager        0/1     1            0           45s
basic-auth-plugin   1/1     1            1           45s
faas-idler          0/1     1            0           45s
gateway             0/1     1            0           45s
nats                1/1     1            1           45s
prometheus          1/1     1            1           45s
queue-worker        1/1     1            1           45s

Как только установка закончена, выход должен выглядеть так:

NAME                READY   UP-TO-DATE   AVAILABLE   AGE
alertmanager        1/1     1            1           75s
basic-auth-plugin   1/1     1            1           75s
faas-idler          1/1     1            1           75s
gateway             1/1     1            1           75s
nats                1/1     1            1           75s
prometheus          1/1     1            1           75s
queue-worker        1/1     1            1           75s

4. Проверьте статус развертывания Ворота развертывание:

kubectl rollout status -n openfaas deploy/gateway

В следующем примере вывод показывает, что Ворота Развертывание было успешно выпущено:

deployment "gateway" successfully rolled out

5. Используйте Kubectl Port-Forward командование для пересылки всех запросов, сделанных в http://localhost: 8080 к стручке, управляющему Ворота услуга:

kubectl port-forward -n openfaas svc/gateway 8080:8080 &
[1] 78674
Forwarding from 127.0.0.1:8080 -> 8080
Forwarding from [::1]:8080 -> 8080

Обратите внимание, что знак Ampersand ( & ) запускает процесс на заднем плане. Вы можете использовать Работа Команда, чтобы показать статус ваших фоновых процессов:

jobs
[1]  + running    kubectl port-forward -n openfaas svc/gateway 8080:8080

PASSWORD=$(kubectl get secret -n openfaas basic-auth -o jsonpath="{.data.basic-auth-password}" | base64 --decode; echo)

OpenFAAS предоставляет утилиту командной строки, которую вы можете использовать для создания и развертывания функций без сервеса. Вы можете установить его, следуя шагам от Установка страница.

Теперь это OpenFaas и FAAS-CLI Утилита командной строки установлена, вы можете создавать и развертывать функции без сервера, используя встроенный шаблонный двигатель. OpenFAAS предоставляет два типа шаблонов:

  • Классические шаблоны основаны на Классический сторож и использовать STDIO общаться с вашей функцией без сердца. Обратитесь к Watchdog Страница для получения более подробной информации о том, как работает сторожевой пейзаж OpenFAAS.

  • -сторожевого сочетания Шаблоны используют HTTP для связи с вашей функцией без сердца. Эти шаблоны доступны через Openfaas Incubator Репозиторий GitHub.

В этом уроке вы будете использовать Классический шаблон Отказ

1. Разберите следующую команду, чтобы увидеть шаблоны, доступные в официальном магазине:

faas-cli template store list
NAME                     SOURCE             DESCRIPTION
csharp                   openfaas           Classic C# template
dockerfile               openfaas           Classic Dockerfile template
go                       openfaas           Classic Golang template
java8                    openfaas           Classic Java 8 template
node                     openfaas           Classic NodeJS 8 template
php7                     openfaas           Classic PHP 7 template
python                   openfaas           Classic Python 2.7 template
python3                  openfaas           Classic Python 3.6 template
python3-dlrs             intel              Deep Learning Reference Stack v0.4 for ML workloads
ruby                     openfaas           Classic Ruby 2.5 template
node10-express           openfaas-incubator Node.js 10 powered by express template
ruby-http                openfaas-incubator Ruby 2.4 HTTP template
python27-flask           openfaas-incubator Python 2.7 Flask template
python3-flask            openfaas-incubator Python 3.6 Flask template
python3-http             openfaas-incubator Python 3.6 with Flask and HTTP
node8-express            openfaas-incubator Node.js 8 powered by express template
golang-http              openfaas-incubator Golang HTTP template
golang-middleware        openfaas-incubator Golang Middleware template
python3-debian           openfaas           Python 3 Debian template
powershell-template      openfaas-incubator Powershell Core Ubuntu:16.04 template
powershell-http-template openfaas-incubator Powershell Core HTTP Ubuntu:16.04 template
rust                     booyaa             Rust template
crystal                  tpei               Crystal template
csharp-httprequest       distantcam         C# HTTP template
csharp-kestrel           burtonr            C# Kestrel HTTP template
vertx-native             pmlopes            Eclipse Vert.x native image template
swift                    affix              Swift 4.2 Template
lua53                    affix              Lua 5.3 Template
vala                     affix              Vala Template
vala-http                affix              Non-Forking Vala Template
quarkus-native           pmlopes            Quarkus.io native image template
perl-alpine              tmiklas            Perl language template based on Alpine image
node10-express-service   openfaas-incubator Node.js 10 express.js microservice template
crystal-http             koffeinfrei        Crystal HTTP template
rust-http                openfaas-incubator Rust HTTP template
bash-streaming           openfaas-incubator Bash Streaming template

☞ Обратите внимание, что вы можете указать альтернативный магазин для шаблонов. В следующей примерной команде перечислены шаблоны из репозитория с именем Andreipope :

faas-cli template store list -u https://raw.githubusercontent.com/andreipope/my-custom-store/master/templates.json

2. Загрузите официальные шаблоны локально:

faas-cli template pull
Fetch templates from repository: https://github.com/openfaas/templates.git at master
2020/03/11 20:51:22 Attempting to expand templates from https://github.com/openfaas/templates.git
2020/03/11 20:51:25 Fetched 19 template(s) : [csharp csharp-armhf dockerfile go go-armhf java11 java11-vert-x java8 node node-arm64 node-armhf node12 php7 python python-armhf python3 python3-armhf python3-debian ruby] from https://github.com/openfaas/templates.git

☞ По умолчанию приведенная выше команда загружает шаблоны из официального репозитория GitHUB OpenFAAS. Если вы хотите использовать пользовательский репозиторий, вам следует указать URL -адрес вашего репозитория. Следующий пример команда вытаскивает шаблоны из репозитория с именем Andreipope :

faas-cli template pull https://github.com/andreipope/my-custom-store/

3. Чтобы создать новую функцию без сервера, запустите FAAS-CLI NEW Команда указала:

  • Имя вашей новой функции ( appfleet-hello-world )
  • Лэнг Параметр, за которым следует шаблон языка программирования ( node ).
faas-cli new appfleet-hello-world --lang node
Folder: appfleet-hello-world created.
  ___                   _____           ____
 / _ \ _ __   ___ _ __ |  ___|_ _  __ _/ ___|
| | | | '_ \ / _ \ '_ \| |_ / _` |/ _` \___ \
| |_| | |_) |  __/ | | |  _| (_| | (_| |___) |
 \___/| .__/ \___|_| |_|_|  \__,_|\__,_|____/
      |_|


Function created in folder: appfleet-hello-world
Stack file written: appfleet-hello-world.yml

Notes:
You have created a new function which uses Node.js 12.13.0 and the OpenFaaS
Classic Watchdog.

npm i --save can be used to add third-party packages like request or cheerio
npm documentation: https://docs.npmjs.com/

For high-throughput services, we recommend you use the node12 template which
uses a different version of the OpenFaaS watchdog.

На этом этапе ваша структура каталогов должна выглядеть следующим образом:

tree . -L 2
.
├── appfleet-hello-world
│   ├── handler.js
│   └── package.json
├── appfleet-hello-world.yml
└── template
    ├── csharp
    ├── csharp-armhf
    ├── dockerfile
    ├── go
    ├── go-armhf
    ├── java11
    ├── java11-vert-x
    ├── java8
    ├── node
    ├── node-arm64
    ├── node-armhf
    ├── node12
    ├── php7
    ├── python
    ├── python-armhf
    ├── python3
    ├── python3-armhf
    ├── python3-debian
    └── ruby

21 directories, 3 files

Что нужно отметить:

  • AppFleet-Hello-World/Handler.js Файл содержит код вашей неверной функции. Вы можете использовать эхо Команда для перечисления содержимого этого файла:
cat appfleet-hello-world/handler.js
"use strict"

module.exports = async (context, callback) => {
    return {status: "done"}
}

  • Вы можете указать зависимости, необходимые вашей функцией без сервеса в Package.json файл. Автоматически сгенерированный файл — это просто пустая оболочка:
cat appfleet-hello-world/package.json

{
  "name": "function",
  "version": "1.0.0",
  "description": "",
  "main": "handler.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Спецификация Appfleet-Hello-World Функция хранится в appfleet-hello-world.yml файл:

1. Опена appfleet-hello-world.yml Файл в простом текстовом редакторе и обновите изображение поле, подготовив к нему имя пользователя Docker Hub. Следующий пример придает мое имя пользователя ( andrepopescu12 ) к поле изображения:

image: andrepopescu12/appfleet-hello-world:latest

Как только вы внесли это изменение, appfleet-hello-world.yml Файл должен выглядеть похоже на следующее:

version: 1.0
provider:
  name: openfaas
  gateway: http://127.0.0.1:8080
functions:
  appfleet-hello-world:
    lang: node
    handler: ./appfleet-hello-world
    image: /appfleet-hello-world:latest

2. Используйте функцию. Введите Faas-Cli Build Команда указывает -f Аргумент с именем файла YAML, который вы отредактировали на предыдущем шаге ( appfleet-hello-world.yml ):

faas-cli build -f appfleet-hello-world.yml
[0] > Building appfleet-hello-world.
Clearing temporary build folder: ./build/appfleet-hello-world/
Preparing: ./appfleet-hello-world/ build/appfleet-hello-world/function
Building: andreipopescu12/appfleet-hello-world:latest with node template. Please wait..
Sending build context to Docker daemon  10.24kB
Step 1/24 : FROM openfaas/classic-watchdog:0.18.1 as watchdog
 ---> 94b5e0bef891
Step 2/24 : FROM node:12.13.0-alpine as ship
 ---> 69c8cc9212ec
Step 3/24 : COPY --from=watchdog /fwatchdog /usr/bin/fwatchdog
 ---> Using cache
 ---> ebab4b723c16
Step 4/24 : RUN chmod +x /usr/bin/fwatchdog
 ---> Using cache
 ---> 7952724b5872
Step 5/24 : RUN addgroup -S app && adduser app -S -G app
 ---> Using cache
 ---> 33c7f04595d2
Step 6/24 : WORKDIR /root/
 ---> Using cache
 ---> 77b9dee16c79
Step 7/24 : ENV NPM_CONFIG_LOGLEVEL warn
 ---> Using cache
 ---> a3d3c0bb4480
Step 8/24 : RUN mkdir -p /home/app
 ---> Using cache
 ---> 65457e03fcb1
Step 9/24 : WORKDIR /home/app
 ---> Using cache
 ---> 50ab672e5660
Step 10/24 : COPY package.json ./
 ---> Using cache
 ---> 6143e79de873
Step 11/24 : RUN npm i --production
 ---> Using cache
 ---> a41566487c6e
Step 12/24 : COPY index.js ./
 ---> Using cache
 ---> 566633e78d2c
Step 13/24 : WORKDIR /home/app/function
 ---> Using cache
 ---> 04c9de75f170
Step 14/24 : COPY function/*.json ./
 ---> Using cache
 ---> 85cf909b646a
Step 15/24 : RUN npm i --production || :
 ---> Using cache
 ---> c088cbcad583
Step 16/24 : COPY --chown=app:app function/ .
 ---> Using cache
 ---> 192db89e5941
Step 17/24 : WORKDIR /home/app/
 ---> Using cache
 ---> ee2b7d7e8bd4
Step 18/24 : RUN chmod +rx -R ./function     && chown app:app -R /home/app     && chmod 777 /tmp
 ---> Using cache
 ---> 81831389293e
Step 19/24 : USER app
 ---> Using cache
 ---> ca0cade453f5
Step 20/24 : ENV cgi_headers="true"
 ---> Using cache
 ---> afe8d7413349
Step 21/24 : ENV fprocess="node index.js"
 ---> Using cache
 ---> 5471cfe85461
Step 22/24 : EXPOSE 8080
 ---> Using cache
 ---> caaa8ae11dc7
Step 23/24 : HEALTHCHECK --interval=3s CMD [ -e /tmp/.lock ] || exit 1
 ---> Using cache
 ---> 881b4d2adb92
Step 24/24 : CMD ["fwatchdog"]
 ---> Using cache
 ---> 82b586f039df
Successfully built 82b586f039df
Successfully tagged andreipopescu12/appfleet-hello-world:latest
Image: andreipopescu12/appfleet-hello-world:latest built.
[0] < Building appfleet-hello-world done in 2.25s.
[0] Worker done.

Total build time: 2.25s

3. Вы можете перечислить свои изображения докера с:

docker images
REPOSITORY                             TAG                 IMAGE ID            CREATED             SIZE
andreipopescu12/appfleet-hello-world   latest              82b586f039df        25 minutes ago      96MB

1. Вписаться в Docker Hub. Запустите Докер Логин Команда с --username Флаг, за которым следует имя пользователя Docker Hub. Следующий пример команды входит в систему, как AndreiPopescu12 :

docker login --username andreipopescu12

Далее вам будет предложено ввести пароль Docker Hub:

Password:
Login Succeeded

2. Используйте Faas-Cli Push Команда для толкания функции без сервеса в Docker Hub:

faas-cli push -f appfleet-hello-world.yml
The push refers to repository [docker.io/andreipopescu12/appfleet-hello-world]
073c41b18852: Pushed
a5c05e98c215: Pushed
f749ad113dce: Pushed
e4f29400b370: Pushed
b7d0eb42e645: Pushed
84fba0eb2756: Pushed
cf2a3f2bc398: Pushed
942d3272b7d4: Pushed
037b653b7d4e: Pushed
966655dc62be: Pushed
08d8e0925a73: Pushed
6ce16b164ed0: Pushed
d76ecd300100: Pushed
77cae8ab23bf: Pushed
latest: digest: sha256:4150d4cf32e7e5ffc8fd15efeed16179bbf166536f1cc7a8c4105d01a4042928 size: 3447
[0] < Pushing appfleet-hello-world [andreipopescu12/appfleet-hello-world:latest] done.
[0] Worker done.
\

1. В соответствии с вашей функцией без сервера наставление до Docker Hub, войдите в свой локальный экземпляр шлюза OpenFAAS, введя следующую команду:

echo -n $PASSWORD | faas-cli login --username admin --password-stdin

2.Рун FAAS-CLI развертывает Команда для развертывания функции без сервеса:

faas-cli deploy -f appfleet-hello-world.yml
Deploying: appfleet-hello-world.
WARNING! Communication is not secure, please consider using HTTPS. Letsencrypt.org offers free SSL/TLS certificates.
Handling connection for 8080
Handling connection for 8080

Deployed. 202 Accepted.
URL: http://127.0.0.1:8080/function/appfleet-hello-world
\

☞ OpenFAAS предоставляет механизм автоматического масштаба, основанный на количестве запросов в секунду, который читается от Prometheus. Ради простоты мы не будем покрывать автоматическую масштабирование в этом руководстве. Для дальнейшего вашего знания вы можете направить Страница автоматического масштаба Отказ

3. Используйте Список FAAS-CLI Команда, чтобы перечислить функции, развернутые в вашем локальном шлюзе OpenFaas:

faas-cli list

4. Вы можете использовать FAAS-CLI Опишите Метод для получения более подробной информации о Appfleet-Hello-World Функция:

faas-cli describe appfleet-hello-world
Name:                appfleet-hello-world
Status:              Ready
Replicas:            1
Available replicas:  1
Invocations:         1
Image:               andreipopescu12/appfleet-hello-world:latest
Function process:    node index.js
URL:                 http://127.0.0.1:8080/function/appfleet-hello-world
Async URL:           http://127.0.0.1:8080/async-function/appfleet-hello-world
Labels:              faas_function : appfleet-hello-world
Annotations:         prometheus.io.scrape : false

1. Чтобы увидеть вашу функцию без сервера в действии, выпустите FAAS-CLI ANLOKE Команда, указав:

  • -f Флаг с именем файла yaml, который описывает вашу функцию ( appfleet-hello-world.yml )
  • Название вашей функции ( AppFleet-Hello-World )

2.type Ctrl + D. . В следующем примере вывод показывает, что ваша функция без сервезна работает как ожидается:

appfleet
Handling connection for 8080
{"status":"done"}

Функция, которую вы создали, развернули, а затем вызываемая в предыдущих разделах, является просто пустой оболочкой. В этом разделе мы обновим его:

  • Прочитайте имя города из stdin
  • Извлечь прогноз погоды из openweathermap.org
  • Печать на консоли прогноз погоды

1. Создайте учетную запись OpenWeatherMap, следуя инструкциям из Зарегистрируйтесь страница. 2. Ведь в OpenWeatherMap, а затем выберите Ключи API :

3. Из здесь вы можете либо скопировать значение ключа по умолчанию, либо создать новый клавиш API, а затем скопировать его значение:

4. Теперь у вас есть ключ API OpenWeatherMap, вы должны использовать npm установить несколько зависимостей. Следующая команда перемещается в Appfleet-Hello-World каталог а затем устанавливает Get-Stdin и Запрос Пакеты:

cd appfleet-hello-world && npm i --save get-stdin request

5. Поместите содержание Handler.js Файл с помощью:

"use strict"
const getStdin = require('get-stdin')
const request = require('request');

let handler = (req) => {
  request(`http://api.openweathermap.org/data/2.5/weather?q=${req}&?units=metric&APPID=`, function (error, response, body) {
    console.error('error:', error)
    console.log('statusCode:', response && response.statusCode)
    console.log('body:', JSON.stringify(body))
  })
};

getStdin().then(val => {
   handler(val);
}).catch(e => {
  console.error(e.stack);
});

module.exports = handler

☞ Чтобы попробовать эту функцию, замените ключ API OpenWeatherMap.

6. Вы можете использовать FAAS-CLI Удалить Команда удалить функцию, которую вы развернули ранее в этом уроке:

faas-cli remove appfleet-hello-world
Deleting: appfleet-hello-world.
Handling connection for 8080
Removing old function.

7. Теперь, что старая функция была удалена, вы должны восстановить, толкать и развернуть свою модифицированную функцию. Вместо того, чтобы выпускать три отдельные команды, вы можете использовать openfaas-cli вверх команда, как в следующем примере:

faas-cli up -f appfleet-hello-world.yml

[0] > Building appfleet-hello-world.
Clearing temporary build folder: ./build/appfleet-hello-world/
Preparing: ./appfleet-hello-world/ build/appfleet-hello-world/function
Building: andreipopescu12/appfleet-hello-world:latest with node template. Please wait..
Sending build context to Docker daemon  43.01kB
Step 1/24 : FROM openfaas/classic-watchdog:0.18.1 as watchdog
 ---> 94b5e0bef891
Step 2/24 : FROM node:12.13.0-alpine as ship
 ---> 69c8cc9212ec
Step 3/24 : COPY --from=watchdog /fwatchdog /usr/bin/fwatchdog
 ---> Using cache
 ---> ebab4b723c16
Step 4/24 : RUN chmod +x /usr/bin/fwatchdog
 ---> Using cache
 ---> 7952724b5872
Step 5/24 : RUN addgroup -S app && adduser app -S -G app
 ---> Using cache
 ---> 33c7f04595d2
Step 6/24 : WORKDIR /root/
 ---> Using cache
 ---> 77b9dee16c79
Step 7/24 : ENV NPM_CONFIG_LOGLEVEL warn
 ---> Using cache
 ---> a3d3c0bb4480
Step 8/24 : RUN mkdir -p /home/app
 ---> Using cache
 ---> 65457e03fcb1
Step 9/24 : WORKDIR /home/app
 ---> Using cache
 ---> 50ab672e5660
Step 10/24 : COPY package.json ./
 ---> Using cache
 ---> 6143e79de873
Step 11/24 : RUN npm i --production
 ---> Using cache
 ---> a41566487c6e
Step 12/24 : COPY index.js ./
 ---> Using cache
 ---> 566633e78d2c
Step 13/24 : WORKDIR /home/app/function
 ---> Using cache
 ---> 04c9de75f170
Step 14/24 : COPY function/*.json ./
 ---> Using cache
 ---> f5765914bd05
Step 15/24 : RUN npm i --production || :
 ---> Using cache
 ---> a300be28c096
Step 16/24 : COPY --chown=app:app function/ .
 ---> 91cd72d8ad7a
Step 17/24 : WORKDIR /home/app/
 ---> Running in fce50a76475a
Removing intermediate container fce50a76475a
 ---> 0ff17b0a9faf
Step 18/24 : RUN chmod +rx -R ./function     && chown app:app -R /home/app     && chmod 777 /tmp
 ---> Running in 6d0c4c92fac1
Removing intermediate container 6d0c4c92fac1
 ---> 1e543bfbf6b0
Step 19/24 : USER app
 ---> Running in 6d33f5ec237d
Removing intermediate container 6d33f5ec237d
 ---> cb7cf5dfab12
Step 20/24 : ENV cgi_headers="true"
 ---> Running in 972c23374934
Removing intermediate container 972c23374934
 ---> 21c6e8198b21
Step 21/24 : ENV fprocess="node index.js"
 ---> Running in 3be91f9d5228
Removing intermediate container 3be91f9d5228
 ---> aafb7a756d38
Step 22/24 : EXPOSE 8080
 ---> Running in da3183bd88c5
Removing intermediate container da3183bd88c5
 ---> 5f6fd7e66a95
Step 23/24 : HEALTHCHECK --interval=3s CMD [ -e /tmp/.lock ] || exit 1
 ---> Running in a590c91037ae
Removing intermediate container a590c91037ae
 ---> fbe20c32941f
Step 24/24 : CMD ["fwatchdog"]
 ---> Running in 59cd231f0576
Removing intermediate container 59cd231f0576
 ---> 88cd8ac65ade
Successfully built 88cd8ac65ade
Successfully tagged andreipopescu12/appfleet-hello-world:latest
Image: andreipopescu12/appfleet-hello-world:latest built.
[0] < Building appfleet-hello-world done in 13.95s.
[0] Worker done.

Total build time: 13.95s

[0] > Pushing appfleet-hello-world [andreipopescu12/appfleet-hello-world:latest].
The push refers to repository [docker.io/andreipopescu12/appfleet-hello-world]
04643e0c999f: Pushed
db3ccc4403b8: Pushed
24d1d5a62262: Layer already exists
adfa28db7666: Layer already exists
b7d0eb42e645: Layer already exists
84fba0eb2756: Layer already exists
cf2a3f2bc398: Layer already exists
942d3272b7d4: Layer already exists
037b653b7d4e: Layer already exists
966655dc62be: Layer already exists
08d8e0925a73: Layer already exists
6ce16b164ed0: Layer already exists
d76ecd300100: Layer already exists
77cae8ab23bf: Layer already exists
latest: digest: sha256:818d92b10d276d32bcc459e2918cb537051a14025e694eb59a9b3caa0bb4e41c size: 3456
[0] < Pushing appfleet-hello-world [andreipopescu12/appfleet-hello-world:latest] done.
[0] Worker done.

Deploying: appfleet-hello-world.
WARNING! Communication is not secure, please consider using HTTPS. Letsencrypt.org offers free SSL/TLS certificates.
Handling connection for 8080
Handling connection for 8080

Deployed. 202 Accepted.
URL: http://127.0.0.1:8080/function/appfleet-hello-world

☞ Обратите внимание, что вы можете пропустить кнопку или развертывание шагов:

  • Следующая пример команда пропускает нажимной шаг:
faas-cli up -f appfleet-hello-world.yml --skip-push
  • Следующая пример команда пропускает развертывание шага:
faas-cli up -f appfleet-hello-world.yml --skip-deploy

8. Чтобы убедиться, что обновленная функция без сервера работает, как и ожидалось, вызовите ее следующим образом:

faas-cli invoke -f appfleet-hello-world.yml appfleet-hello-world
Reading from STDIN - hit (Control + D) to stop.
Berlin
Handling connection for 8080
Hello, you are currently in Berlin
statusCode: 200
body: "{\"coord\":{\"lon\":13.41,\"lat\":52.52},\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"description\":\"scattered clouds\",\"icon\":\"03d\"}],\"base\":\"stations\",\"main\":{\"temp\":282.25,\"feels_like\":270.84,\"temp_min\":280.93,\"temp_max\":283.15,\"pressure\":1008,\"humidity\":61},\"visibility\":10000,\"wind\":{\"speed\":13.9,\"deg\":260,\"gust\":19},\"clouds\":{\"all\":40},\"dt\":1584107132,\"sys\":{\"type\":1,\"id\":1275,\"country\":\"DE\",\"sunrise\":1584077086,\"sunset\":1584119213},\"timezone\":3600,\"id\":2950159,\"name\":\"Berlin\",\"cod\":200}"

9. Чтобы убрать, запустите FAAS-CLI Удалить Команда с именем вашей функции без сервера ( appfleet-hello-world Как аргумент):

faas-cli remove appfleet-hello-world
Deleting: appfleet-hello-world.
Handling connection for 8080
Removing old function.

OpenFAAS предоставляет веб-интерфейс на основе веб-сайта. В этом разделе вы узнаете, как вы можете использовать его для развертывания функции без сервера.

1. Сначала вы должны использовать эхо Команда для получения пароля

echo $PASSWORD
49IoP28G8247MZcj6a1FWUYUx

2. Раскрыть браузер и посетить http://localhost: 8080 Отказ Войти в систему, используйте Админ имя пользователя и пароль, который вы получили на предыдущем шаге. Вы будете перенаправлены на домашнюю страницу OpenFaas. Выберите Развернуть новую функцию кнопка:

3. будет отображаться новое окно. Выберите Пользовательский Вкладка, а затем введите:

  • docker.io/andreipopescu12/appfleet-hello-world в Docker Image поле ввода
  • Appfleet-Hello-World в Название функции поле ввода

4.once вы заполнили Docker Image. и Название функции Входные коробки, выберите Развертывание кнопка:

5. Ваша новая функция будет видна в левой панели навигации. Нажмите здесь:

Вы будете перенаправлены на страницу функции Invoke:

6. В Запросить тело Входная ящик, введите имя города, для которого вы хотите получить прогноз погоды, а затем выберите Вызвать кнопка:

Если все работает хорошо, прогноз погоды будет отображаться в Тело ответа поле:

Gateway OpenFAAS разоблачает следующие показатели:

В этом разделе вы узнаете, как настроить Prometheus и Grafana для отслеживания здоровья ваших функций без серверов.

1. Использование Следующая команда для перечисления ваших развертываний:

kubectl get deployments -n openfaas -l "release=openfaas, app=openfaas"
NAME                READY   UP-TO-DATE   AVAILABLE   AGE
alertmanager        1/1     1            1           15m
basic-auth-plugin   1/1     1            1           15m
faas-idler          1/1     1            1           15m
gateway             1/1     1            1           15m
nats                1/1     1            1           15m
prometheus          1/1     1            1           15m
queue-worker        1/1     1            1           15m

2. Чтобы разоблачить Прометей Развертывание, создайте объект службы с именем PROMETHEUS-UI :

kubectl expose deployment prometheus -n openfaas --type=NodePort --name=prometheus-ui

service/prometheus-ui exposed

--type = NodePort Флаг открывает PROMETHEUS-UI Сервис на каждом из IP -адресов узла. Также, а Clusterip Сервис создан. Вы будете использовать это, чтобы подключиться к PROMETHEUS-UI Сервис снаружи кластера.

3. Проверьте PROMETHEUS-UI Сервис, введите следующую команду:

kubectl get svc prometheus-ui -n openfaas
NAME            TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
prometheus-ui   NodePort   10.96.129.204           9090:31369/TCP   8m1s

4.Forward Все запросы, сделанные в http://localhost: 9090 к стручке, управляющему PROMETHEUS-UI услуга:

kubectl port-forward -n openfaas svc/prometheus-ui 9090:9090 &

5.Не, вы можете указать свой браузер на http://localhost: 9090 , и вы должны увидеть страницу, аналогичную следующему скриншоту:

6. Чтобы развернуть Grafana, вы Stefanprodan/Faas-Grafana: 4.6.3 изображение. Запустите следующую команду:

kubectl run grafana -n openfaas --image=stefanprodan/faas-grafana:4.6.3 --port=3000
kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
deployment.apps/grafana created

7. Теперь вы можете перечислить свои развертывания с:

kubectl get deployments -n openfaas
NAME                READY   UP-TO-DATE   AVAILABLE   AGE
alertmanager        1/1     1            1           46m
basic-auth-plugin   1/1     1            1           46m
faas-idler          1/1     1            1           46m
gateway             1/1     1            1           46m
grafana             1/1     1            1           107s
nats                1/1     1            1           46m
prometheus          1/1     1            1           46m
queue-worker        1/1     1            1           46m

8. Используйте следующее kubectl развертывает развертывание Команда создать объект службы, который разоблачает Графана развертывание:

kubectl expose deployment grafana -n openfaas --type=NodePort --name=grafa
service/grafana exposed

9. Повторите подробную информацию о вашем новом сервисе с:

kubectl get service grafana -n openfaas
NAME      TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
grafana   NodePort   10.96.194.59           3000:32464/TCP   60s

10. Для того, чтобы все запросы сделаны в http://localhost: 3030 к стручке, управляющему Графана услуга:

kubectl port-forward -n openfaas svc/grafana 3000:3000 &
[3] 3973
Forwarding from 127.0.0.1:3000 -> 3000
Forwarding from [::1]:3000 -> 3000

11. Теперь вы настроили пересылку порта, вы можете получить доступ к Grafana, указав свой браузер на http://localhost: 3000:

12.log в Grafana с использованием имени пользователя Админ и пароль админ . Домашняя приборная панель Страница будет отображаться:

13. из левого меню, выберите Монитоны -> Импорт :

14.Type https://grafana.com/grafana/dashboards/3434 в Grafana.com Dashboard поле ввода. Затем выберите Нагрузка кнопка:

15. В Импорт панели панели Диалоговое окно, установите источник данных Prometheus на FAAS , а затем выберите Импорт :

Будет отображаться пустая панель инструментов:

16. Теперь вы можете вызвать свою функцию пару раз, используя FAAS-CLI ANLOKE Команда следующим образом:

faas-cli invoke -f appfleet-hello-world.yml appfleet-hello-world

17. Подключите обратно в окно браузера, открытое графану. Ваша панель инструментов должна автоматически обновляться и выглядеть аналогично следующему скриншоту:

Мы надеемся, что этот урок был полезен для изучения оснований развертывания без серверов функций с OpenFAAS. Для получения дополнительных отличных уроков о Docker и Kubernetes, мы рекомендуем вам посетить нашу блог .

Спасибо за чтение!

Оригинал: «https://dev.to/appfleet/create-serverless-functions-with-openfaas-37ob»