Serverless ya está aquí. Lo sabemos. Incluso para las empresas que están comenzando su viaje en la nube moviéndose a plataformas basadas en contenedores, ya saben que serverless está en su visión futura al menos para algunos casos de uso específicos.
Su simplicidad sin necesidad de preocuparse por nada relacionado con la plataforma solo se enfoca en el código y también la economía que viene con ellos hace que este modelo de computación sea un cambio de juego.
La plataforma principal para este enfoque en este momento es AWS Lambda de Amazon, hemos leído y escuchado mucho sobre AWS Lambda, pero todas las plataformas van por ese camino. Google con sus Google Functions, Microsoft con su Azure. Esto no es solo una cosa para los proveedores de nube pública, también si estás operando en un enfoque de nube privada puedes usar este modo de implementación usando frameworks como KNative o OpenFaaS. Si necesitas más detalles al respecto, también tuvimos algunos artículos sobre este tema:
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 […]
Todas estas plataformas están actualizando y mejorando su opción para ejecutar cualquier tipo de código que desees en ellas, y esto es lo que Azure Function acaba de anunciar hace unas semanas, el lanzamiento de un enfoque de Custom Handler para soportar cualquier tipo de lenguaje que puedas imaginar:
Azure Functions custom handlers
Learn to use Azure Functions with any language or runtime version.
Y vamos a probar eso haciendo lo que más nos gusta ………..
Lo primero que necesitamos hacer es crear nuestra aplicación Flogo. Voy a usar Flogo Enterprise para hacer eso, pero puedes hacer lo mismo usando la versión de código abierto también:
Vamos a crear una aplicación simple, solo un servicio REST de Hello World. Como puedes ver aquí:
El archivo JSON de la aplicación Flogo puedes encontrarlo en el repositorio de GitHub que se muestra a continuación:
GitHub - alexandrev/flogo-azure-function: Sample of Flogo Application running as a Azure Function
Sample of Flogo Application running as a Azure Function - GitHub - alexandrev/flogo-azure-function: Sample of Flogo Application running as a Azure Function
Pero las configuraciones principales son las siguientes:
El servidor escuchará en el puerto especificado por la variable de entorno FUNCTIONS_HTTPWORKER_PORT
El servidor escuchará una solicitud GET en la URI /hello-world
La respuesta será bastante simple “Invocando una aplicación Flogo dentro de Azure Functions”
Ahora, que tenemos el archivo JSON, solo necesitamos comenzar a crear los artefactos necesarios para ejecutar una función de Azure.
Necesitaremos instalar el paquete npm para las Azure Functions. Para hacer eso necesitamos ejecutar el siguiente comando:
npm i -g azure-functions-core-tools@3 --unsafe-perm true
Es importante tener el “@3” porque de esa manera hacemos referencia a la versión que tiene esta nueva lógica de Custom Handler para poder ejecutarla.
Crearemos una nueva carpeta llamada flogo-func y ejecutaremos el siguiente comando dentro de esa carpeta:
func init --docker
Ahora deberíamos seleccionar node como el entorno de ejecución a usar y javascript como el lenguaje. Eso podría ser algo extraño porque no vamos a usar ni node, ni dotnet ni python ni powershell. Pero seleccionaremos eso para mantenerlo simple ya que solo intentamos enfocarnos en el enfoque de Docker para hacerlo.
Después de eso solo necesitamos crear una nueva función, y para hacer eso necesitamos escribir el siguiente comando:
func new
En la interfaz basada en CLI que nos muestra las Azure Function Core Tools, solo necesitamos seleccionar HTTP trigger y proporcionar un nombre.
En nuestro caso, usaremos hello-world como el nombre para mantenerlo similar a lo que definimos como parte de nuestra aplicación Flogo. Terminaremos con la siguiente estructura de carpetas:
Ahora necesitamos abrir la carpeta que se ha creado y necesitamos hacer varias cosas:
Primero que todo, necesitamos eliminar el archivo index.js porque no necesitamos ese archivo ya que esta no será una función de node JS.
Necesitamos copiar el HelloWorld.json (nuestra aplicación Flogo) a la carpeta raíz de la función.
Necesitamos cambiar el archivo host.json al siguiente contenido:
Ahora, necesitamos generar el engine-windows-amd64.exe y para poder hacer eso necesitamos ir al FLOGO_HOME en nuestra máquina e ir a la carpeta FLOGO_HOME/flogo/<VERSION>/bin y lanzar el siguiente comando:
./builder-windows-amd64.exe build
Y deberías obtener el engine-windows-amd64.exe como salida como puedes ver en la imagen a continuación:
Ahora, solo necesitas copiar ese archivo dentro de la carpeta de tu función, y deberías tener la siguiente estructura de carpetas como puedes ver aquí:
Y una vez que tengas eso, solo necesitas ejecutar tu función para poder probarla localmente:
func start
Después de ejecutar ese comando deberías ver una salida similar a la que se muestra a continuación:
¡Solo me gustaría resaltar el tiempo de inicio para nuestra aplicación Flogo alrededor de 15 milisegundos! Ahora, solo necesitas probarlo usando cualquier navegador y solo ir a la siguiente URL:
http://localhost:7071/api/hello-world
Este ha sido solo el primer paso en nuestro viaje, pero fueron los pasos necesarios para poder ejecutar nuestra aplicación Flogo como parte de tu entorno serverless alojado por la plataforma Microsoft Azure!
Serverless is already here. We know that. Even for companies that are starting their cloud journey moving to container-based platforms, they already know that serverless is in their future view at least for some specific use cases.
Its simplicity without needed to worry about anything related to the platform just focuses on the code and also the economics that comes with them makes this computing model a game-changer.
The mainstream platform for this approach at this moment is AWS Lambda from Amazon, we have read and heard a lot of AWS Lamba, but all the platforms are going to that path. Google with its Google Functions, Microsoft with its Azure. This is not just a thing for public cloud providers, also if you’re running on a private cloud approach you can use this deployment mode using frameworks like KNative or OpenFaaS. If you need more details about it, also we had some articles about this topic:
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 […]
All of these platforms are updating and enhancing its option to execute any kind of code that you want on it, and this is what Azure Function just announced some weeks ago, the release of a Custom Handler approach to support any kind of language that you could think about:
Azure Functions custom handlers
Learn to use Azure Functions with any language or runtime version.
And we’re going to test that doing what we’d like best ………..
The first thing we need to do is to create our Flogo Application. I’m going to use Flogo Enterprise to do that, but you can do the same using the Open Source version as well:
We’re going to create a simple application just a Hello World REST service. As you can see here:
The JSON file of the Flogo Application you can find it in the GitHub repository shown below:
GitHub - alexandrev/flogo-azure-function: Sample of Flogo Application running as a Azure Function
Sample of Flogo Application running as a Azure Function - GitHub - alexandrev/flogo-azure-function: Sample of Flogo Application running as a Azure Function
But the main configurations are the following ones:
Server will listen on the port specified by the environment variable FUNCTIONS_HTTPWORKER_PORT
Server will listen for a GET request on the URI /hello-world
Response will be quite simple “Invoking a Flogo App inside Azure Functions”
Now, that we have the JSON file, we only need to start creating the artifacts needed to run an Azure Function.
We will need to install the npm package for the Azure Functions. To do that we need to run the following command:
npm i -g azure-functions-core-tools@3 --unsafe-perm true
It is important to have the “@3” because that way we reference the version that has this new Custom Handler logic to be able to execute it.
We will create a new folder call flogo-func and run the following command inside that folder:
func init --docker
Now we should select node as the runtime to be used and javascriptas the language. That could be something strange because we are going to use neither node, nor dotnet or pythonor powershell. But we will select that to keep it simple as we just try to focus on the Docker approach to do that.
After that we just need to create a new function, and to do that we need to type the following command:
func new
In the CLI-based interface that the Azure Function Core Tools shows us, we just need to select HTTP trigger and provide a name.
In our case, we will use hello-world as the name to keep it similar to what we defined as part of our Flogo Application. We will end up with the following folder structure:
Now we need to open the folder that is has been created and we need to do several things:
First of all, we need to remove the index.js file because we don’t need that file as this will not be a node JS function.
We need to copy the HelloWorld.json (our Flogo application) to the root folder of the function.
We need to change the host.json file to the following content:
Now, we need to generate the engine-windows-amd64.exe and to be able to do that we need to go to the FLOGO_HOME in our machine and go to the folder FLOGO_HOME/flogo/<VERSION>/bin and launch the following command:
./builder-windows-amd64.exe build
And you should get the engine-windows-amd64.exe as the output as you can see in the picture below:
Now, you just need to copy that file inside the folder of your function, and you should have the following folder structure as you can see here:
And once you have that, you just need to run your function to be able to test it locally:
func start
After running that command you should see an output similar to the one shown below:
I’d just like to highlight the startup time for our Flogo application around 15 milliseconds!!! Now, you only need to test it using any browser and just go to the following URL:
http://localhost:7071/api/hello-world
This has been just the first step on our journey but it was the steps needed to be able to run our Flogo application as part of your serverless environment hosted by Microsoft Azure platform!