Saltar al contenido

Desplegando la aplicación Flogo en OpenFaaS

OpenFaaS es una alternativa para habilitar el enfoque sin servidor en tu infraestructura cuando no estás operando en la nube pública y no tienes disponibles esas otras opciones como AWS Lambda Functions o Azure Functions, o incluso en la nube pública, te gustaría las características y opciones de personalización que proporciona.

OpenFaaS® (Funciones como Servicio) es un marco para construir funciones sin servidor con Docker y Kubernetes que tiene soporte de primera clase para métricas. Cualquier proceso puede ser empaquetado como una función, permitiéndote consumir una variedad de eventos web sin codificación repetitiva de plantilla.

Hay buen contenido en Medium sobre OpenFaaS, así que no me gusta pasar mucho tiempo en esto, pero me gustaría dejarte aquí algunos enlaces como referencia:

Ya tenemos mucha información sobre cómo ejecutar una aplicación Flogo como una función Lambda, como puedes ver aquí:

https://www.youtube.com/watch?v=TysuwbXODQI

Pero… ¿qué pasa con OpenFaaS? ¿Podemos ejecutar nuestra aplicación Flogo dentro de OpenFaaS? ¡Claro! Déjame explicarte cómo.

OpenFaaS es un marco muy personalizable para construir funciones de escala cero y podría necesitar algo de tiempo para familiarizarse con los conceptos. Todo se basa en watchdogs que son los componentes que escuchan las solicitudes y son responsables de lanzar los forks para manejar las solicitudes:

Vamos a usar el nuevo watchdog llamado of-watchdog que se espera sea el predeterminado en el futuro y toda la información está aquí:

Este watchdog proporciona varios modos, uno de ellos se llama HTTP y es el predeterminado, y se basa en un reenvío HTTP al servidor interno que se ejecuta en el contenedor. Eso encaja perfectamente con nuestra aplicación Flogo y significa que lo único que necesitamos es desplegar un disparador de solicitud HTTP Receive en nuestra aplicación Flogo y eso es todo.

Las únicas cosas que necesitas configurar son el método (POST) y la Ruta (/) para poder manejar las solicitudes. En nuestro caso vamos a hacer una aplicación simple de Hola Mundo como puedes ver aquí:

Para poder ejecutar esta aplicación necesitamos usar varias cosas, y vamos a explicarlo aquí:

Primero que nada, necesitamos hacer la instalación del entorno OpenFaaS, voy a omitir todos los detalles sobre este proceso y solo señalarte al tutorial detallado sobre ello:

Ahora necesitamos crear nuestra plantilla y para hacerlo, vamos a usar una plantilla de Dockerfile. Para crearla vamos a ejecutar:

faas-cli new --lang dockerfile

Vamos a nombrar la función flogo-test. Y ahora vamos a actualizar el Dockerfile para que sea así:

La mayor parte de este contenido es común para cualquier otra plantilla que use el nuevo of-watchdog y el modo HTTP.

Me gustaría resaltar las siguientes cosas:

Usamos varias variables de entorno para definir el comportamiento:

  • mode = HTTP para definir que vamos a usar este método
  • upstream_url = URL a la que vamos a reenviar la solicitud
  • fprocess = Comando del sistema operativo que necesitamos ejecutar, en nuestro caso significa ejecutar la aplicación Flogo.

Otras cosas son las mismas que deberías hacer en caso de que quieras ejecutar aplicaciones Flogo en Docker:

  • Agregar el ejecutable del motor para tu plataforma (UNIX en la mayoría de los casos ya que la base de la imagen es casi siempre basada en Linux)
  • Agregar el archivo JSON de la aplicación que deseas usar.

También necesitamos cambiar el archivo yml para que se vea así:

version: 1.0
provider:
  name: openfaas
  gateway: http://abc59586cc33f11e9941b069251daa7b-1114483165.eu-west-2.elb.amazonaws.com:8080
functions:
  flogo-test:
    lang: dockerfile
    handler: ./flogo-test
    image: alexandrev/flogo-test:1.7

¡Y eso es todo! Ahora, solo necesitamos ejecutar el siguiente comando:

faas-cli up -f .flogo-test.yml

Y la función se va a desplegar en tu entorno y podemos ejecutarla usando el portal de OpenFaaS directamente:

Todo el código está disponible aquí (lo único que falta es el Flogo Enterprise Engine que necesitas usar para poder construirlo y subirlo)

Etiquetas:

Deploying Flogo App on OpenFaaS

OpenFaaS is an alternative to enable the serverless approach in your infrastructure when you’re not running in the public cloud and you don’t have available those other options like AWS Lambda Functions or Azure Functions or even in public cloud, you’d like the features and customizations option it provides.

OpenFaaS® (Functions as a Service) is a framework for building serverless functions with Docker and Kubernetes which has first-class support for metrics. Any process can be packaged as a function enabling you to consume a range of web events without repetitive boiler-plate coding.

There is good content on medium about OpenFaaS so I don’t like to spend so much time on this, but I’d like to leave you here some links for reference:

We already have a lot of info about how to run a Flogo Application as a Lambda Function as you can see here:

https://www.youtube.com/watch?v=TysuwbXODQI

But.. what about OpenFaaS? Can we run our Flogo application inside OpenFaaS? Sure! Let me explain to you how.

OpenFaaS is a very customize framework to build zero-scaled functions and it could need some time to get familiar with concepts. Everything is based on watchdogs that are the components listening to the requests are responsible for launching the forks to handle the requests:

We’re going to use the new watchdog named as of-watchdog that is the one expected to be the default one in the feature and all the info is here:

This watchdog provides several modes, one of them is named HTTP and it is the default one, and is based on some HTTP Forward to the internal server running in the container. That fits perfectly with our Flogo application and means that the only thing we need is to deploy an HTTP Receive Request trigger in our Flogo Application and that’s it.

The only things you need to configure is the method (POST) and the Path (/) to be able to handle the requests. In our case we’re going to do a simple Hello World app as you can see here:

To be able to run this application we need to use several things, and let’s explain it here:

First of all, we need to do the installation of the OpenFaaS environment, I’m going to skip all the details about this process and just point to you to the detailed tutorial about it:

Now we need to create our template and to do that, we are going to use a Dockerfile template. To create it we’re going to execute:

faas-cli new --lang dockerfile

We’re going to name the function flogo-test. And now we’re going to update the Dockerfile to be like this:

Most of this content is common for any other template using the new of-watchdog and the HTTP mode.

I’d like to highlight the following things:

We use several environment variables to define the behavior:

  • mode = HTTP to define what we’re going to use this method
  • upstream_url = URL that we are going to forward the request to
  • fprocess = OS command that we need to execute, in our case means to run the Flogo App.

Other things are the same as you should do in case you want to run flogo apps in Docker:

  • Add the engine executable for your platform (UNIX in most cases as the image base is almost always a Linux based)
  • Add the JSON file of the application that you want to use.

We also need to change the yml file to look like this:

version: 1.0
provider:
  name: openfaas
  gateway: http://abc59586cc33f11e9941b069251daa7b-1114483165.eu-west-2.elb.amazonaws.com:8080
functions:
  flogo-test:
    lang: dockerfile
    handler: ./flogo-test
    image: alexandrev/flogo-test:1.7

And that’s it! Now, we only need to execute the following command:

faas-cli up -f .\flogo-test.yml

And the function is going to be deployed to your environment and we can run it using the OpenFaas portal directly:

All the code is available here (the only thing left is the Flogo Enterprise Engine that you need to use to be able to build and upload it)