Saltar al contenido

Cómo mejorar la productividad en el desarrollo de cargas de trabajo de Kubernetes

timelapse photo of highway during golden hour

La telepresencia es la forma de reducir el tiempo entre tus líneas de código y una carga de trabajo nativa de la nube en ejecución.

foto de lapso de tiempo de la autopista durante la hora dorada
Foto de Joey Kyber en Unsplash

Todos sabemos cómo las cargas de trabajo nativas de la nube y Kubernetes han cambiado la forma en que hacemos las cosas. Hay muchos beneficios que vienen con el efecto de la contenedorización y las plataformas de orquestación como Kubernetes, y hemos discutido mucho sobre ello: escalabilidad, autocuración, autodescubrimiento, resiliencia, y así sucesivamente.

Pero se han planteado algunos desafíos, la mayoría de ellos en el aspecto operativo en el que tenemos muchos proyectos enfocados en abordar, pero generalmente olvidamos lo que el embajador ha definido como el “ciclo de desarrollo interno”.

El “ciclo de desarrollo interno” es el flujo de trabajo productivo que cada desarrollador sigue al trabajar en una nueva aplicación, servicio o componente. Este flujo iterativo es donde codificamos, probamos lo que hemos codificado y arreglamos lo que no funciona o mejoramos lo que ya tenemos.

Este flujo ha existido desde el principio de los tiempos; no importa si estabas codificando en C usando la biblioteca STD o COBOL a principios de 1980 o haciendo nodejs con los últimos marcos y bibliotecas a tu disposición.

Hemos visto movimientos hacia hacer este ciclo interno más efectivo, especialmente en el desarrollo front-end. Tenemos muchas opciones para ver el último cambio que hemos hecho en el código, solo guardando el archivo. Pero por primera vez, cuando el movimiento hacia una plataforma basada en contenedores, este flujo hace que los desarrolladores sean menos productivos.

La razón principal es que el número de tareas que un desarrollador necesita hacer ha aumentado. Imagina este conjunto de pasos que necesitamos realizar:

  • Construir la aplicación
  • Construir la imagen del contenedor
  • Desplegar la imagen del contenedor en Kubernetes

Estas acciones no son tan rápidas como probar tus cambios localmente, haciendo que los desarrolladores sean menos productivos que antes, que es lo que el proyecto “telepresencia” está tratando de resolver.

La telepresencia es un proyecto incubador de la CNCF que ha centrado mucha atención recientemente porque se ha incluido OOTB en las últimas versiones del componente Docker Desktop. Basado en sus propias palabras, esta es la definición del proyecto de telepresencia:

La telepresencia es una herramienta de código abierto que permite a los desarrolladores codificar y probar microservicios localmente contra un clúster de Kubernetes remoto. La telepresencia facilita flujos de trabajo de desarrollo más eficientes aliviando la necesidad de preocuparse por otras dependencias de servicio.

Ok, entonces, ¿cómo podemos empezar? Vamos a sumergirnos juntos. Lo primero que necesitamos hacer es instalar la telepresencia en nuestro clúster de Kubernetes:

Nota: También hay una forma de instalar telepresencia usando Helm en tu clúster siguiendo estos pasos:

helm repo add datawire  https://app.getambassador.io
helm repo update
kubectl create namespace ambassador
helm install traffic-manager --namespace ambassador datawire/telepresence

Ahora crearé un contenedor simple que alojará una aplicación Golang que expone un servicio REST simple y lo haré más accesible; seguiré el tutorial que está disponible a continuación; tú también puedes hacerlo.

Una vez que tengamos nuestra aplicación golang lista, vamos a generar el contenedor a partir de ella, usando el siguiente Dockerfile:

FROM golang:latest

RUN apt-get update
RUN apt-get upgrade -y

ENV GOBIN /go/bin

WORKDIR /app

COPY *.go ./
RUN go env -w GO111MODULE=off
RUN go get .
RUN go build -o /go-rest
EXPOSE 8080
CMD [ "/go-rest" ]

Luego, una vez que tengamos la aplicación, la subiremos al servidor de Kubernetes y la ejecutaremos como un despliegue, como puedes ver en la imagen a continuación:

kubectl create deployment rest-service --image=quay.io/alexandrev/go-test  --port=8080
kubectl expose deploy/rest-service

Una vez que tengamos eso, es el momento de comenzar a ejecutar la telepresencia, y comenzaremos a conectarnos al clúster usando el siguiente comando telepresence connect, y mostrará una salida como esta:

Luego vamos a listar los puntos finales disponibles para interceptar con el comando telepresence list y veremos nuestro servicio-rest que hemos expuesto antes:

Ahora, ejecutaremos el interceptor específico, pero antes de eso, vamos a hacer el truco para que podamos conectarlo a nuestro Visual Studio Code. Generaremos un archivo launch.json en Visual Studio Code con el siguiente contenido:

{
    // Usa IntelliSense para aprender sobre posibles atributos.
    // Pasa el ratón para ver descripciones de atributos existentes.
    // Para más información, visita: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Lanzar con archivo env",
            "type": "go",
            "request": "launch",
            "mode": "debug",
            "program": "1",
            "envFile": "NULL/go-debug.env"
           }
    ]
}

La parte interesante aquí es el argumento envFile que apunta a un archivo inexistente go-debug.env en la misma carpeta, por lo que necesitamos asegurarnos de que generamos ese archivo cuando hacemos la intercepción. Así que usaremos el siguiente comando:

telepresence intercept rest-service --port 8080:8080 --env-file /Users/avazquez/Data/Projects/GitHub/rest-golang/go-debug.env

Y ahora, podemos comenzar nuestra sesión de depuración en Visual Studio Code y tal vez agregar un punto de interrupción y algunas líneas, como puedes ver en la imagen a continuación:

Entonces, ahora, si golpeamos el pod en Kubernetes, veremos cómo se alcanza el punto de interrupción como si estuviéramos en una sesión de depuración local.

Eso significa que podemos inspeccionar variables y todo, cambiar el código o hacer lo que necesitemos para acelerar nuestro desarrollo!

How To Improve Your Kubernetes Workload Development Productivity

timelapse photo of highway during golden hour

Telepresence is the way to reduce the time between your lines of code and a cloud-native workload running.

timelapse photo of highway during golden hour
Photo by Joey Kyber on Unsplash

We all know how cloud-native workloads and Kubernetes have changed how we do things. There are a lot of benefits that come with the effect of containerization and orchestration platforms such as Kubernetes, and we have discussed a lot about it: scalability, self-healing, auto-discovery, resilience, and so on.

But some challenges have been raised, most of them on the operational aspect that we have a lot of projects focused on tackling, but usually, we forget about what the ambassador has defined as the “inner dev cycle.”

The “inner dev cycle” is the productive workflow that each developer follows when working on a new application, service, or component. This iterative flow is where we code, test what we’ve coded, and fix what is not working or improve what we already have.

This flow has existed since the beginning of time; it doesn’t matter if you were coding in C using STD Library or COBOL in the early 1980 or doing nodejs with the latest frameworks and libraries at your disposal.

We have seen movements towards making this inner cycle more effective, especially in front-end development. We have many options to see the last change we have done in code, just saving the file. But for the first time when the movement to a container-based platform, this flow makes devs less productive.

The main reason is that the number of tasks a dev needs to do has increased. Imagine this set of steps that we need to perform:

  • Build the app
  • Build the container image
  • Deploy the container image in Kubernetes

These actions are not as fast as testing your changes locally, making devs less productive than before, which is what the “telepresence” project is trying to solve.

Telepresence is an incubator project from the CNCF that has recently focused a lot of attention because it has included OOTB in the latest releases of the Docker Desktop component. Based on its own words, this is the definition of the telepresence project:

Telepresence is an open-source tool that lets developers code and test microservices locally against a remote Kubernetes cluster. Telepresence facilitates more efficient development workflows while relieving the need to worry about other service dependencies.

Ok, so let’s see how we can start? Let’s dive in together. The first thing we need to do is to install telepresence in our Kubernetes cluster:

Note: It is also a way to install telepresence using Helm in your cluster following these steps:

helm repo add datawire  https://app.getambassador.io
helm repo update
kubectl create namespace ambassador
helm install traffic-manager --namespace ambassador datawire/telepresence

Now I will create a simple container that will host a Golang application that exposes a simple REST service and make it more accessible; I will follow the tutorial that is available below; you can do it as well.

Once we have our golang application ready, we are going to generate the container from it, using the following Dockerfile:

FROM golang:latest

RUN apt-get update
RUN apt-get upgrade -y

ENV GOBIN /go/bin

WORKDIR /app

COPY *.go ./
RUN go env -w GO111MODULE=off
RUN go get .
RUN go build -o /go-rest
EXPOSE 8080
CMD [ "/go-rest" ]

Then once we have the app, we’re going to upload to the Kubernetes server and run it as a deployment, as you can see in the picture below:

kubectl create deployment rest-service --image=quay.io/alexandrev/go-test  --port=8080
kubectl expose deploy/rest-service

Once we have that, it is the moment to start executing the telepresence, and we will start connecting to the cluster using the following command telepresence connect, and it will show an output like this one:

Then we are going to list the endpoints available to intercept with the command telepresence listand we will see our rest-service that we have exposed before:

Now, we will run the specific interceptor, but before that, we’re going to do the trick so we can connect it to our Visual Studio Code. We will generate a launch.json file in Visual Studio Code with the following content:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch with env file",
            "type": "go",
            "request": "launch",
            "mode": "debug",
            "program": "1",
            "envFile": "NULL/go-debug.env"
           }
    ]
}

The interesting part here is the envFile argument that points to a non-existent file go-debug.env on the same folder, so we need to make sure that we generate that file when we do the interception. So we will use the following command:

telepresence intercept rest-service --port 8080:8080 --env-file /Users/avazquez/Data/Projects/GitHub/rest-golang/go-debug.env

And now, we can start our debug session in Visual Studio code and maybe add a breakpoint and some lines, as you can see in the picture below:

So, now, if we hit the pod in Kubernetes, we will see how the breakpoint is being reached as we were in a local debugging session.

That means that we can inspect variables and everything, change the code, or do whatever we need to speed up our development!

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *