<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mathis Joffre on Medium]]></title>
        <description><![CDATA[Stories by Mathis Joffre on Medium]]></description>
        <link>https://medium.com/@mjoffre?source=rss-83556ffe3621------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aVgOZt8f3537sBfPIZxiOg.jpeg</url>
            <title>Stories by Mathis Joffre on Medium</title>
            <link>https://medium.com/@mjoffre?source=rss-83556ffe3621------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 04:54:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mjoffre/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Unifying Kubernetes: Embrace the Power of Karmada for Seamless Multi-Cloud Management!]]></title>
            <link>https://faun.pub/unifying-kubernetes-embrace-the-power-of-karmada-for-seamless-multi-cloud-management-9b2481ca8b87?source=rss-83556ffe3621------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b2481ca8b87</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Mathis Joffre]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 13:02:30 GMT</pubDate>
            <atom:updated>2023-09-08T09:31:58.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/442/0*mIC17MKf-RiBVKsR.png" /><figcaption>Karmada logo</figcaption></figure><p>In this captivating article, we explore how Karmada revolutionizes your multi-cloud strategy. Imagine effortlessly orchestrating Kubernetes clusters across GCP and AWS, eliminating silos and complexity. Unleash the true potential of cross-platform deployment, management, and scalability — all with one game-changing tool. Dive into the world of Karmada and unlock a new era of streamlined cloud-native operations!</p><h4><strong>What is Karmada?</strong></h4><p>In the ever-evolving landscape of cloud-native solutions, the need to efficiently manage multiple Kubernetes clusters deployed on different platforms has become a critical challenge. Enter Karmada, a game-changing Kubernetes-based multi-cluster management system designed to simplify the complexity of cross-platform orchestration.</p><p>Imagine a world where deploying, managing, and monitoring applications across diverse Kubernetes clusters can be accomplished effortlessly from a single, centralized control plane. Karmada turns this vision into reality by providing a robust kube-api server architecture that seamlessly operates on top of other kube-api servers.</p><p>At its core, Karmada acts as the ultimate control plane, empowering you to oversee multiple clusters coherently, irrespective of their deployment platforms or unique configurations. Gone are the days of juggling separate management scripts and struggling to navigate different control interfaces. With Karmada, you can harness the full potential of Kubernetes without getting lost in the complexities of multi-cluster administration.</p><p>In this article, we delve deep into the capabilities of Karmada, exploring how it revolutionizes Kubernetes management and unlocks unparalleled synergy among clusters. Embark on a journey to discover how Karmada reshapes the landscape of multi-cloud application deployment, streamlining processes and enhancing your organization’s agility in today’s dynamic cloud-native world. Let’s dive in and witness the power of unified Kubernetes management with Karmada.</p><h4><strong>Karmada Architecture</strong></h4><p>At its essence, Karmada serves as a seamless extension of the widely recognized Kubernetes internal architecture, operating as a Kubernetes cluster that expertly manages other Kubernetes clusters. Picture it as the conductor orchestrating a harmonious symphony among your distributed clusters. Let’s delve into the Karmada architecture and explore this remarkable capability.</p><figure><img alt="Karmada architecture diagram showing that’s almost the same architecture as Kubernetes" src="https://cdn-images-1.medium.com/max/551/0*Q1vOLnsqzqg1nn5g.png" /><figcaption>Karmada internal architecture</figcaption></figure><p>With Karmada, the beauty lies in its simplicity. You can effortlessly harness its potential by using familiar tools and workflows, just as you would with any standard Kubernetes cluster. Utilize the trusty kubectl to interact with Karmada, and witness the magic unfold as you deploy your applications to the managed clusters. The rest? Handled seamlessly by Karmada, leaving you free to focus on your application development and business goals.</p><p>The most remarkable aspect of Karmada is its inherent synergy with your existing Kubernetes know-how. As you manage multiple clusters with ease, you’ll appreciate the comfort of familiarity, knowing that Karmada empowers you with the same tools and workflows you’ve grown accustomed to. The learning curve? Virtually eliminated. The potential for streamlined multi-cluster management? Limitless.</p><h4><strong>What makes Karmada so special?</strong></h4><p>Karmada bring with it two new API definitions, namely the PropagationPolicy and the OverridePolicy. These APIs are the key to unlocking the true potential of Karmada, enabling you to seamlessly manage multiple clusters with ease. Let’s explore these APIs in more detail.</p><p><strong>PropagationPolicy</strong></p><p>The PropagationPolicy API is the heart of Karmada, defining the rules for propagating resources across clusters. It is a custom resource definition (CRD) that looks like this:</p><pre>apiVersion: policy.karmada.io/v1alpha1<br>kind: PropagationPolicy<br>metadata:<br>  name: nginx-propagation<br>spec:<br>  resourceSelectors:<br>    - apiVersion: apps/v1<br>      kind: Deployment<br>      name: nginx<br>  placement:<br>    clusterAffinity:<br>      clusterNames:<br>        - member1<br>        - member2<br>    replicaScheduling:<br>      replicaDivisionPreference: Weighted<br>      replicaSchedulingType: Divided<br>      weightPreference:<br>        staticWeightList:<br>          - targetCluster:<br>              clusterNames:<br>                - member1<br>            weight: 1<br>          - targetCluster:<br>              clusterNames:<br>                - member2<br>            weight: 1</pre><p>The PropagationPolicy API defines the following:</p><ul><li>The resourceSelectors field specifies the resources to be propagated across clusters. In this example, we are propagating the nginx deployment.</li><li>The placement field specifies the target clusters for the propagation. In this example, we are propagating the nginx deployment to the member1 and member2 clusters.</li><li>The replicaScheduling field specifies the scheduling strategy for the replicas. In this example, we are using the Divided strategy, which divides the replicas evenly across the target clusters.</li></ul><p>Thanks to that you don’t have to modify your application manifests to deploy them to multiple clusters. Instead, you can simply create a PropagationPolicy to define the rules for propagating the resources across clusters.</p><p><strong>OverridePolicy</strong></p><p>The OverridePolicy is here to cover the cases where you need to override the resource definitions in the target clusters. For exemple, if you want to modify ENV variables depending on a cloud provider, you can use the OverridePolicy to do so. It is a custom resource definition (CRD) that looks like this:</p><pre>apiVersion: policy.karmada.io/v1alpha1<br>kind: OverridePolicy<br>metadata:<br>  name: nginx-op<br>spec:<br>  resourceSelectors:<br>    - apiVersion: apps/v1<br>      kind: Deployment<br>      name: nginx<br>  overrideRules:<br>    - targetCluster:<br>        clusterNames:<br>          - member2<br>      overriders:<br>        labelsOverrider:<br>          - operator: add<br>            value:<br>              env: skoala-dev<br>          - operator: add<br>            value:<br>              env-stat: skoala-stage<br>          - operator: remove<br>            value:<br>              for: for<br>          - operator: replace<br>            value:<br>              bar: test<br>    - targetCluster:<br>        clusterNames:<br>          - member1<br>      overriders:<br>        annotationsOverrider:<br>          - operator: add<br>            value:<br>              env: skoala-stage<br>          - operator: remove<br>            value:<br>              bom: bom<br>          - operator: replace<br>            value:<br>              emma: sophia</pre><p>The OverridePolicy API defines the following:</p><ul><li>The resourceSelectors field specifies the resources to be overridden in the target clusters. In this example, we are overriding the nginx deployment.</li><li>The overrideRules field specifies the override rules for the target clusters. In this example, we are overriding the nginx deployment in the member1 and member2 clusters.</li><li>The overriders field specifies the override rules for the target clusters. For example, we are overriding the labels and annotations of the nginx deployment in the member1 and member2 clusters.</li></ul><h4><strong>Karmada in Action</strong></h4><p>Now that we’ve explored the Karmada architecture and its core APIs, let’s dive into the world of multi-cluster management with Karmada. In this section, we’ll walk through a step-by-step example of deploying an application across multiple clusters using Karmada. Let’s get started!</p><p><strong>Step 1: Deploy Karmada</strong></p><p>The first step is to deploy Karmada. You can do this by following the instructions in the <a href="https://karmada.io/docs/get-started/nginx-example">Karmada documentation</a>.</p><p>Normally, you’ll have this output at the end of the installation:</p><pre>Local Karmada is running.<br><br>To start using your Karmada environment, run:<br>  export KUBECONFIG=&quot;$HOME/.kube/karmada.config&quot;<br>Please use &#39;kubectl config use-context karmada-host/karmada-apiserver&#39; to switch the host and control plane cluster.<br><br>To manage your member clusters, run:<br>  export KUBECONFIG=&quot;$HOME/.kube/members.config&quot;<br>Please use &#39;kubectl config use-context member1/member2/member3&#39; to switch to the different member cluster.</pre><p><strong>Step 2: Deploy the application</strong></p><p>The next step is to deploy the application. You can use any application you want, but for this example, we’ll use the nginx application. You can deploy the application by following the instructions in the <a href="https://karmada.io/docs/get-started/nginx-example">Karmada documentation</a>.</p><p>Normally, you’ll have this output at the end of the deployment:</p><pre>deployment.apps/nginx created</pre><p>But if we check the deployment, we’ll see that the pods are not running:</p><pre>NAMESPACE   NAME    READY   UP-TO-DATE   AVAILABLE   AGE<br>nginx       nginx   0/2     0            0           21s</pre><p>This is because the nginx deployment is not propagated to the member clusters yet. We have to add a PropagationPolicy to propagate the nginx deployment to the member clusters.</p><p><strong>Step 3: Add a PropagationPolicy</strong></p><p>The next step is to add a PropagationPolicy to propagate the nginx deployment to the member clusters. You can do this by following the instructions in the <a href="https://karmada.io/docs/get-started/nginx-example">Karmada documentation</a>.</p><p>Normally, you’ll have this output at the end of the deployment:</p><pre>propagationpolicy.policy.karmada.io/nginx-propagation created</pre><p>If we check the pods again, we’ll see that the pods are running:</p><pre>NAMESPACE   NAME    READY   UP-TO-DATE   AVAILABLE   AGE<br>nginx       nginx   2/2     2            2           21s</pre><p>This is because the nginx deployment is propagated to the member clusters.</p><p><strong>Step 4: Check the application</strong></p><p>If you context switch to the member clusters, you’ll see that the nginx deployment is propagated to the member clusters:</p><pre>$ kubectl config use-context member1<br>Switched to context &quot;member1&quot;.<br>$ kubectl get deployment<br>NAME    READY   UP-TO-DATE   AVAILABLE   AGE<br>nginx   1/1     1            1           21s<br>$ kubectl config use-context member2<br>Switched to context &quot;member2&quot;.<br>$ kubectl get deployment<br>NAME    READY   UP-TO-DATE   AVAILABLE   AGE<br>nginx   1/1     1            1           21s</pre><p>As you can see, the nginx deployment is propagated to the member clusters evenly. This is because we used the Divided strategy in the PropagationPolicy.</p><h4><strong>Conclusion</strong></h4><p>In this article, we explored the power of Karmada, a revolutionary multi-cluster management system that empowers you to orchestrate Kubernetes clusters across different platforms with ease. We delved into the Karmada architecture, discovering how it seamlessly integrates with your existing Kubernetes know-how. We also explored the core APIs of Karmada, namely the PropagationPolicy and the OverridePolicy, which enable you to effortlessly manage multiple clusters with ease.</p><p>If you like this article, please give it a clap. If you have any questions or comments, please leave them in the comments section below. Thank you for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*S9osLi5TzdkIQcgp.png" /></figure><h4>👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇</h4><h4>🚀<a href="http://from.faun.to/r/8zxxd">Join FAUN Developer Community &amp; Get Similar Stories in your Inbox Each Week</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b2481ca8b87" width="1" height="1" alt=""><hr><p><a href="https://faun.pub/unifying-kubernetes-embrace-the-power-of-karmada-for-seamless-multi-cloud-management-9b2481ca8b87">Unifying Kubernetes: Embrace the Power of Karmada for Seamless Multi-Cloud Management!</a> was originally published in <a href="https://faun.pub/">FAUN.dev() 🐾</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying MicroVM on Top of Kubernetes]]></title>
            <link>https://medium.com/better-programming/deploying-microvm-on-top-of-kubernetes-64ca39743040?source=rss-83556ffe3621------2</link>
            <guid isPermaLink="false">https://medium.com/p/64ca39743040</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[virtualization]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Mathis Joffre]]></dc:creator>
            <pubDate>Sat, 11 Feb 2023 16:00:27 GMT</pubDate>
            <atom:updated>2023-02-13T18:00:54.463Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying microVM on Top of Kubernetes</h3><h4>Fast and secure microVM fitted for serverless workload directly into Kubernetes</h4><figure><img alt="Kubernetes logo" src="https://cdn-images-1.medium.com/max/512/0*zhiHBWN8P9LJVgoA.png" /><figcaption>Kubernetes logo</figcaption></figure><p>In this tutorial, we will deploy a microVM on top of Kubernetes. We will use the <a href="https://katacontainers.io/">Kata Containers</a> runtime to run the microVM. The microVM will be deployed as a pod in Kubernetes.</p><p>If you are unfamiliar with microVM, I’ve recently written a <a href="https://medium.com/better-programming/getting-started-with-firecracker-a88495d656d9">Medium article</a> about it. You can read it to get more information about microVM, Firecracker, and how you can deploy it from scratch.</p><p>If you are unfamiliar with Kubernetes, you can read the <a href="https://kubernetes.io/docs/home/">Kubernetes documentation here.</a></p><p>You may now wonder why you should use microVMs instead of containers. The answer is simple: microVMs are more secure than containers, as they give a hardware virtualization layer. This means that microVMs will be isolated from the host, which is not the case for containers. This is why microVMs are more secure than containers and are used by companies like AWS, Google, etc., to run their serverless services.</p><p>The following diagram explains the difference between containers and microVMs:</p><figure><img alt="Container VS VM — Architectural diagram" src="https://cdn-images-1.medium.com/max/601/1*fNuKiEv9Bc8K_9eji-fPyw.png" /><figcaption>Container VS VM — Architectural diagram</figcaption></figure><p>Before we start, let’s see the prerequisites.</p><h3>Prerequisites</h3><ul><li>A Kubernetes cluster with at least one node. Yes, it is quite obvious, but who knows? :)</li><li>KVM is installed on the node. You can check if it is installed by running the following command:</li></ul><pre>$ lsmod | grep kvm</pre><p>If you don’t see any output, you need to install KVM. You can find the installation instructions <a href="https://www.linux-kvm.org/page/Downloads">here</a>.</p><h3>Some Challenges</h3><p>Before we start, let’s see the challenges we need to solve to deploy a microVM on top of Kubernetes.</p><h4>PID 1</h4><p>PID 1 is the first process (init process) executed when the microVM starts. This process is responsible for initializing the microVM.</p><p>In the case of a container, there is no init process because the container is not a real operating system. The container is just a process running on the host operating system.</p><p>We need to have an init process to ship our container as a microVM.</p><h4>Expose a Container Runtime Interface to make the microVM compatible with Kubernetes</h4><p>The Container Runtime Interface (CRI) is the standard interface used by the kubelet to manage the containers. It is a set of gRPC primitives that the kubelet uses to interact with the container runtime. Thanks to the CRI, the kubelet can create, start, stop, delete, etc., the containers without knowing the implementation details of the container runtime.</p><p>Without the CRI, the kubelet cannot manage the microVM. So, we need to expose a CRI to the kubelet to make the microVM compatible with Kubernetes.</p><p>Unfortunately, Virtual Machine Manager (VMM) does not expose a CRI. So, we need to implement a shim that will expose a CRI to the kubelet. This shim will be responsible for the communication between the kubelet and the VMM.</p><p>If you want to know more about the CRI, you can read the <a href="https://kubernetes.io/docs/concepts/architecture/cri/">Kubernetes documentation</a></p><h4>Pause container</h4><p>The pause container is used to hold the network namespace of the pod. It keeps the network namespace alive until the pod is deleted. The pause container is created by the kubelet and is not managed by the CRI but holds the resources of the pod.</p><p>If the pause container holds resources and the microVM doesn’t support hot plug, the microVM will start with the resources held by the pause container. This is not what we want.</p><p>We want the microVM to be able to support pod resource resizing.</p><p>If you want to know more about the pause container, you can read <a href="https://www.ianlewis.org/en/almighty-pause-container">this excellent article</a>.</p><h3>Kata Containers</h3><p>One solution to solve the challenges mentioned above is to use Kata Containers. Kata Containers is a container runtime that is compatible with Kubernetes. It is designed to run untrusted workloads on top of Kubernetes. It is compatible with Virtual Machine Managers (VMM) like QEMU, Firecracker, etc.</p><p>If you want to know more about it, just <a href="https://katacontainers.io/">click here</a>.</p><h4>Kata Containers architecture</h4><p>The following diagram shows the architecture of Kata Containers:</p><figure><img alt="Architecture diagram of Kata Containers" src="https://cdn-images-1.medium.com/max/1024/0*jjzOwc9u7R2iNYqR.jpg" /><figcaption><a href="https://katacontainers.io/learn/">source</a></figcaption></figure><p>As you can see, Kata containers genuinely leverage the already-built container ecosystem.</p><p>First, Kata containers act as a shim between the kubelet and the VMM: They are responsible for the communication between them. It uses the containerd plugin architecture to expose a CRI to the kubelet.</p><p>Second, Kata containers own its own filesystem, where an agent runs. This agent is like a PID 1. It is responsible for the initialization of the microVM and for starting the container workload into the microVM using runC.</p><p>Third, Kata containers manage the agent through a VSOCK exposed by the microVM to the host. This VSOCK is used to communicate with the agent. The agent is responsible for communicating between the microVM and the container workload.</p><p>Finally, Kata containers can manage the microVM through different VMMs like QEMU, Firecracker, etc. Some of them support hot plug, which means the microVM can be resized without restarting it.</p><p>Thanks to Kata Containers, we can deploy a microVM on top of Kubernetes without trouble due to the abovementioned challenges.</p><h3>Deploying a microVM on Top of Kubernetes</h3><p>In this section, we will deploy a microVM on top of Kubernetes. We will use the Kata Containers runtime to run the microVM, and the microVM will be deployed as a pod in Kubernetes.</p><h4>Installing Kata Containers</h4><p>First, we need to install Kata Containers. You can find the installation instructions <a href="https://github.com/kata-containers/kata-containers/tree/main/docs/install">here</a>.</p><p>If you are using a Vanilla Kubernetes Cluster, you can install Kata Containers by running the following commands:</p><pre>$ kubectl apply -f https://raw.githubusercontent.com/kata-containers/kata-containers/main/tools/packaging/kata-deploy/kata-rbac/base/kata-rbac.yaml<br>$ kubectl apply -f https://raw.githubusercontent.com/kata-containers/kata-containers/main/tools/packaging/kata-deploy/kata-deploy/base/kata-deploy-stable.yaml<br>$ kubectl -n kube-system wait --timeout=10m --for=condition=Ready -l name=kata-deploy pod<br>$ kubectl apply -f https://raw.githubusercontent.com/kata-containers/kata-containers/main/tools/packaging/kata-deploy/runtimeclasses/kata-runtimeClasses.yaml</pre><p>And that’s it! Kata Containers is installed on your Kubernetes cluster as DaemonSets. Easy, right?</p><h4>Deploying a microVM</h4><p>When Kata Containers is available on your Kubernetes cluster, you can deploy a microVM by specifying a runtime class.</p><p>The following manifest shows how to deploy a microVM on top of Kubernetes using cloud-hypervisor as the VMM:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  labels:<br>    run: php-apache-kata-clh<br>  name: php-apache-kata-clh<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      run: php-apache-kata-clh<br>  template:<br>    metadata:<br>      labels:<br>        run: php-apache-kata-clh<br>    spec:<br>      runtimeClassName: kata-clh<br>      containers:<br>        - image: k8s.gcr.io/hpa-example<br>          imagePullPolicy: Always<br>          name: php-apache<br>          ports:<br>            - containerPort: 80<br>              protocol: TCP<br>          resources:<br>            requests:<br>              cpu: 200m<br>      restartPolicy: Always<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: php-apache-kata-clh<br>spec:<br>  ports:<br>    - port: 80<br>      protocol: TCP<br>      targetPort: 80<br>  selector:<br>    run: php-apache-kata-clh<br>  sessionAffinity: None<br>  type: ClusterIP</pre><p>As you can see, we have specified the runtime class kata-clh in the pod manifest. This will tell the kubelet to use the Kata Containers runtime to run the microVM using cloud-hypervisor as VMM.</p><p>If you want to know more about the provided Kata Containers runtime classes, you can read the <a href="https://github.com/kata-containers/kata-containers/blob/main/tools/packaging/kata-deploy/README.md#run-a-sample-workload">Kata Containers documentation</a>.</p><h4>Testing the microVM</h4><p>Now that the microVM is deployed, we can test it.</p><p>We will use the kubectl port-forward command to forward the port 80 of the microVM to port 80 of the host:</p><pre>$ kubectl port-forward service/php-apache-kata-clh 80:80</pre><p>If everything is working, you should see be able to connect to the microVM using your browser by going to <a href="http://localhost/">http://localhost:80/</a>.</p><h3>Conclusion</h3><p>In this article, we have seen how to deploy a microVM on top of Kubernetes. We have seen that Kata Containers is a great solution for running a microVM on top of Kubernetes. We have also seen how to deploy a microVM using Kata Containers and cloud-hypervisor as VMM.</p><h3>References</h3><ul><li><a href="https://kubernetes.io/docs">Kubernetes documentation</a></li><li><a href="https://github.com/kata-containers/kata-containers/tree/main/docs">Kata Containers documentation</a></li><li><a href="https://github.com/kata-containers/kata-containers">Kata Containers project</a></li><li><a href="https://katacontainers.io/">Kata Containers&#39; official website</a></li></ul><pre><strong>Want to Connect?</strong><br><br>If you enjoyed this article, you can see more on Medium<br>or chat with me on <a href="https://twitter.com/JoffreMathis">Twitter</a>.<br><br>Also, if you have any questions, feel free to ask them in the comments. <br>I will be happy to answer them.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64ca39743040" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/deploying-microvm-on-top-of-kubernetes-64ca39743040">Deploying MicroVM on Top of Kubernetes</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With Firecracker]]></title>
            <link>https://medium.com/better-programming/getting-started-with-firecracker-a88495d656d9?source=rss-83556ffe3621------2</link>
            <guid isPermaLink="false">https://medium.com/p/a88495d656d9</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mathis Joffre]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 17:16:40 GMT</pubDate>
            <atom:updated>2023-02-09T07:41:14.294Z</atom:updated>
            <content:encoded><![CDATA[<h4>Secure and fast microVMs for serverless computing.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*pHJwlVbjY5TPLQY2.jpg" /></figure><p>You may have heard about <a href="https://firecracker-microvm.github.io/">Firecracker</a>, a new open source virtualization technology that is built for serverless computing. Firecracker is a virtual machine monitor that runs on top of <a href="https://www.linux-kvm.org/page/Main_Page">KVM</a>. The following diagram shows how does it work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*Pmc_2lY1-oK-ZzgA2AnJDA.png" /><figcaption><a href="https://thenewstack.io/how-firecracker-is-going-to-set-modern-infrastructure-on-fire/">Source</a></figcaption></figure><p><a href="https://firecracker-microvm.github.io/">Firecracker</a> is a great fit for serverless computing, where you need to run a lot of small, single-purpose, and short-lived microVMs.</p><p>In this article, we will show you how to install <a href="https://firecracker-microvm.github.io/">Firecracker</a> on your Linux machine and run your first microVM.</p><h3>Prerequisites</h3><p>To follow this tutorial, you will need:</p><ul><li>A Linux machine with <a href="https://www.linux-kvm.org/page/Main_Page">KVM</a> installed. You can check if <a href="https://www.linux-kvm.org/page/Main_Page">KVM</a> is installed by running the following command:</li></ul><pre>$ lsmod | grep kvm</pre><ul><li>The latest version of <a href="https://firecracker-microvm.github.io/">Firecracker</a>. You can download it from the <a href="https://github.com/firecracker-microvm/firecracker/releases">Firecracker releases page</a>.</li><li>The getting started kernel and root filesystem. You can download them following the<a href="https://github.com/firecracker-microvm/firecracker/blob/main/docs/getting-started.md#running-firecracker"> getting-started steps</a>.</li></ul><h3>Installing Firecracker</h3><p><a href="https://firecracker-microvm.github.io/">Firecracker</a> is distributed as a static binary. You can download the latest version from the <a href="https://github.com/firecracker-microvm/firecracker/releases">Firecracker releases page</a>. Once you have downloaded the binary, you can install it by running the following commands:</p><pre>$ sudo setfacl -m u:${USER}:rw /dev/kvm<br>$ release_url=&quot;https://github.com/firecracker-microvm/firecracker/releases&quot;<br>$ latest=$(basename $(curl -fsSLI -o /dev/null -w  %{url_effective} ${release_url}/latest))<br>$ arch=`uname -m`<br>$ curl -L ${release_url}/download/${latest}/firecracker-${latest}-${arch}.tgz | tar -xz<br>$ mv release-${latest}-$(uname -m)/firecracker-${latest}-$(uname -m) firecracker</pre><h3>Running your first microVM</h3><p>Now you can run your first microVM, it is like running a regular Linux machine. You can run a microVM by running the following commands:</p><pre>$ export kernel_path=$(pwd)&quot;/hello-vmlinux.bin&quot;<br>$ export rootfs_path=$(pwd)&quot;/hello-rootfs.ext4&quot;<br>$ firecracker --api-sock /tmp/firecracker.socket<br>$ curl --unix-socket /tmp/firecracker.socket -i \<br>    -X PUT &#39;http://localhost/boot-source&#39; \<br>    -H &#39;Accept: application/json&#39; \<br>    -H &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>        &quot;kernel_image_path&quot;: &quot;${kernel_path}&quot;,<br>        &quot;boot_args&quot;: &quot;console=ttyS0 reboot=k panic=1 pci=off&quot;<br>    }&#39;<br>$ curl --unix-socket /tmp/firecracker.socket -i \<br>    -X PUT &#39;http://localhost/drives/rootfs&#39; \<br>    -H &#39;Accept: application/json&#39; \<br>    -H &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>        &quot;drive_id&quot;: &quot;rootfs&quot;,<br>        &quot;path_on_host&quot;: &quot;${rootfs_path}&quot;,<br>        &quot;is_root_device&quot;: true,<br>        &quot;is_read_only&quot;: false<br>    }&#39;<br>$ curl --unix-socket /tmp/firecracker.socket -i \<br>    -X PUT &#39;http://localhost/actions&#39; \<br>    -H  &#39;Accept: application/json&#39; \<br>    -H  &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>        &quot;action_type&quot;: &quot;InstanceStart&quot;<br>    }&#39;</pre><p>The first command starts the <a href="https://firecracker-microvm.github.io/">Firecracker</a> process. The second command configures the kernel image and the boot arguments. The third command configures the root filesystem. The last command starts the microVM.</p><h4>Adding a network interface</h4><p>Ok, now you have a running microVM, but it is not very useful. You can add a network interface to your microVM by running the following command:</p><pre>$ curl --unix-socket /tmp/firecracker.socket -i \<br>    -X PUT &#39;http://localhost/network-interfaces/eth0&#39; \<br>    -H  &#39;Accept: application/json&#39; \<br>    -H  &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>        &quot;iface_id&quot;: &quot;eth0&quot;,<br>        &quot;guest_mac&quot;: &quot;AA:FC:00:00:00:01&quot;,<br>        &quot;host_dev_name&quot;: &quot;tap0&quot;<br>    }&#39;</pre><p>This command adds a network interface to the microVM and must be executed before starting it.</p><p>The guest_mac is the MAC address of the microVM.</p><p>The host_dev_name is the name of the tap device on the host. You can create the tap device by running the following commands:</p><pre>$ sudo ip tuntap add dev tap0 mode tap user $USER<br>$ sudo ip addr add 172.16.0.1/24 dev tap0<br>$ sudo ip link set tap0 up<br>$ sudo sh -c &quot;echo 1 &gt; /proc/sys/net/ipv4/ip_forward&quot;<br>$ sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE<br>$ sudo iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT<br>$ sudo iptables -A FORWARD -i tap0 -o eth0 -j ACCEPT</pre><p>Then, once VM is booted, set up the network inside the guest as follows:</p><pre>$ ip addr add 172.16.0.2/24 dev eth0<br>$ ip link set eth0 up<br>$ ip route add default via 172.16.0.1 dev eth0</pre><h4>Snapshot you microVM</h4><p>A snapshot is a copy of the microVM memory and the guest’s storage at a given point in time. You can use snapshots to boot a microVM faster.</p><p>Let’s say you have a microVM that is configured and running. You can create a snapshot of the microVM by running the following commands:</p><pre>$ curl --unix-socket /tmp/firecracker.socket -i \<br>    -X PATCH &#39;http://localhost/vm&#39; \<br>    -H &#39;Accept: application/json&#39; \<br>    -H &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>            &quot;state&quot;: &quot;Paused&quot;<br>    }&#39;<br>$ curl --unix-socket /tmp/firecracker.socket -i \<br>    -X PUT &#39;http://localhost/snapshot/create&#39; \<br>    -H  &#39;Accept: application/json&#39; \<br>    -H  &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>        &quot;snapshot_path&quot;: &quot;mem_file_path&quot;,<br>        &quot;mem_file_path&quot;: &quot;snapshot_path&quot;,<br>        &quot;version&quot;: &quot;2.0.0&quot;<br>    }&#39;<br>$ curl --unix-socket /tmp/firecracker.socket -i \<br>    -X PATCH &#39;http://localhost/vm&#39; \<br>    -H &#39;Accept: application/json&#39; \<br>    -H &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>            &quot;state&quot;: &quot;Resumed&quot;<br>    }&#39;</pre><p>These commands pause the microVM, then create a snapshot of the microVM and finally resume it. The snapshot_path is the path to the snapshot file.</p><p>The mem_file_path is the path to the memory file. The version is the snapshot version. You can restore the microVM from the snapshot by running the following command:</p><pre>$ curl --unix-socket /tmp/firecracker.socket -i \<br>    -X PUT &#39;http://localhost/snapshot/load&#39; \<br>    -H  &#39;Accept: application/json&#39; \<br>    -H  &#39;Content-Type: application/json&#39; \<br>    -d &#39;{<br>        &quot;snapshot_path&quot;: &quot;snapshot_path&quot;,<br>        &quot;mem_file_path&quot;: &quot;mem_file_path&quot;,<br>        &quot;enable_diff_snapshots&quot;: false,<br>        &quot;resume_vm&quot;: false<br>    }&#39;</pre><p>This command restores the microVM from the snapshot and resumes it. The enable_diff_snapshots is a boolean that enables or disables differential snapshots.</p><h3>Run containers on Firecracker</h3><p>You’re maybe wondering if you can run containers on <a href="https://firecracker-microvm.github.io/">Firecracker</a>. The answer is yes, you can run containers on <a href="https://firecracker-microvm.github.io/">Firecracker</a>.</p><h4>Firecracker-containerd</h4><p>To do so, we need to use<a href="https://github.com/firecracker-microvm/firecracker-containerd"> firecracker-containerd</a>.<a href="https://github.com/firecracker-microvm/firecracker-containerd"> firecracker-containerd </a>is a daemon that manages the Firecracker microVMs that run containers. You can install <a href="https://github.com/firecracker-microvm/firecracker-containerd">firecracker-containerd</a> following the <a href="https://github.com/firecracker-microvm/firecracker-containerd/blob/main/docs/quickstart.md">instructions</a></p><p><a href="https://github.com/firecracker-microvm/firecracker-containerd">Firecracker-containerd</a> relies on <a href="https://containerd.io/">containerd</a>, the following diagram shows how<a href="https://github.com/firecracker-microvm/firecracker-containerd"> firecracker-containerd</a> works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*RkZ5BqpgdIzj2iWXowdGBA.png" /><figcaption><a href="https://github.com/firecracker-microvm/firecracker-containerd/blob/main/docs/architecture.md">Source</a></figcaption></figure><p>To sum up, <a href="https://github.com/firecracker-microvm/firecracker-containerd">firecracker-containerd</a> creates a microVM for each container.</p><p>The microVM is configured with a root filesystem and a kernel image. The root filesystem contains an agent which is able to manage containers using <a href="https://github.com/opencontainers/runc">runc</a>. The microVM is started by containerd-shim. The containerd-shim is a process that is started by <a href="https://containerd.io/">containerd</a>. Thanks to the vSock, the containerd-shim can communicate with the agent inside the microVM. The agent is able to manage containers using <a href="https://github.com/opencontainers/runc">runc</a>. The agent is also responsible for managing the container lifecycle. With this architecture, you can run containers on <a href="https://firecracker-microvm.github.io/">Firecracker</a> and benefit from the security and performance of <a href="https://firecracker-microvm.github.io/">Firecracker</a>. Plus, you can use microVMs inside <a href="https://kubernetes.io/">Kubernetes</a>.</p><h4>Running a container</h4><p>Now you can run a container by running the following command:</p><pre>$ sudo ctr run --runtime io.containerd.firecracker.v1 -t docker.io/library/alpine:latest test sh</pre><p>This command runs a container using the <a href="https://github.com/firecracker-microvm/firecracker-containerd">firecracker-containerd</a> runtime. The `-t` flag is used to allocate a pseudo-TTY. The `docker.io/library/alpine:latest` is the image to use. The `test` is the name of the container. The `sh` is the command to run inside the container.</p><h4>Connecting to the container</h4><p>Now you can connect to the container by running the following command:</p><pre>$ sudo ctr t exec --exec-id test sh</pre><p>This command connects to the container. The ` — exec-id` is the name of the container. The `sh` is the command to run inside the container.</p><h3>Conclusion</h3><p>In this article, you have learned how to use <a href="https://firecracker-microvm.github.io/">Firecracker</a>. You have also learned how to run containers on <a href="https://firecracker-microvm.github.io/">Firecracker</a>. I hope you enjoyed this article. If you have any questions, feel free to ask them in the comments.</p><h4>Further reading</h4><ul><li><a href="https://github.com/firecracker-microvm/firecracker/tree/main/docs">Firecracker documentation</a></li><li><a href="https://github.com/firecracker-microvm/firecracker">Firecracker on GitHub</a></li><li><a href="https://github.com/firecracker-microvm/firecracker-containerd/tree/main/docs">Firecracker-containerd documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a88495d656d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/getting-started-with-firecracker-a88495d656d9">Getting Started With Firecracker</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simply reduce your cloud carbon footprint]]></title>
            <link>https://medium.com/dotfair/simply-reduce-your-cloud-carbon-footprint-f0fe9708cf3f?source=rss-83556ffe3621------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0fe9708cf3f</guid>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[carbon-footprint]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[green]]></category>
            <dc:creator><![CDATA[Mathis Joffre]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 21:36:26 GMT</pubDate>
            <atom:updated>2023-01-09T09:15:09.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*CHb6ZOxYK_-QHBgh.jpg" /></figure><p>According to the <a href="https://www.oreilly.com/radar/the-cloud-in-2021-adoption-continues/">O’Reilly survey</a> more than <strong>90% of organizations</strong> <strong>use the</strong> <strong>cloud</strong> in 2021. It shows that the last pandemic accelerates cloud adoption, but what are the environmental impact of this massive shift into cloud? Is this shift compatible with the IPCC (Intergovernmental Panel on Climate Change) goals?</p><p>To answer those questions, let’s dive into IT carbon footprint.</p><h3><strong>Overview of IT footprint</strong></h3><p><a href="https://theshiftproject.org/en/article/unsustainable-use-online-video/">In 2019, IT accounted for at least <strong>4% of the greenhouse gas emissions</strong></a> which is two times more than civil aviation. With an overall increase of 9% per year, in 2025 IT carbon footprint could double. In this 4%, data-centers usage represents 19%. It is almost 1% of the greenhouse gas emission.</p><p>This trend is quite worrying when we see how climate change impacts our world and is shaping our future, but shifting to the cloud might be a strong asset to reduce it.</p><h3>Cloud carbon footprint</h3><p>Overall cloud helps the industry to reduce their footprint, thanks to:</p><ul><li><strong>Collocation of customer workloads</strong>: instead of running multiple oversized servers on-premise, cloud providers mutualize resources in their data-centers increasing overall efficiency.</li><li><strong>On-demand compute</strong>: industries can use compute only when needed. Reducing number of idle servers.</li><li><strong>Centralization of compute into efficient data-center</strong>: cloud providers tend to create more sustainable data-centers, where companies can host their applications lowering their number of servers.</li><li><strong>Agreements signed with energy providers</strong>: cloud providers manage to use mostly renewable energy.</li></ul><p>Therefore, companies don’t need to worry about their footprint in cloud. You think so?</p><h4>Jevons paradox</h4><p>Let’s me introduce to you the jevons paradox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/0*FDQHxgNtnVdoH2t3" /></figure><blockquote>Jevons says that improvements in <a href="https://en.wikipedia.org/wiki/Fuel_efficiency">fuel efficiency</a> tend to increase (rather than decrease) fuel use: “It is a confusion of ideas to suppose that the economical use of fuel is equivalent to diminished consumption. The very contrary is the truth</blockquote><p>Are you saying that as cloud footprint is better, organizations will tend to use it more, thus increase the footprint of their infrastructure? Yes, that is exactly the point!</p><p>As cloud is scalable and offering a wide range of services, companies tends to use cloud more and more increasing, by definition, the overall footprint of their IT. This overconsumption of resources isn’t only an environmental risk but also a financial risk for customers.</p><h4>How reducing its cloud footprint benefits to companies’ finances</h4><p>Since the beginning of the Ukrainian-Russian war, cost of energy is increasing, thus impacting all the business model of cloud providers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VOjiphxRTn0FOzzO" /><figcaption><a href="https://ec.europa.eu/eurostat/web/products-eurostat-news/-/ddn-20221031-1">https://ec.europa.eu/eurostat/web/products-eurostat-news/-/ddn-20221031-1</a></figcaption></figure><p>As we know energy consumption and carbon footprint is correlated, meaning that reducing its carbon footprint benefits to the billing. A greenops strategy is indeed a finops approach.</p><p>That is why, most companies must incubate greenops into their teams, but what tools can help them to do so.</p><h3>Follow your cloud carbon footprint with .FAIR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdKIPHzaqemigB7YCMc8eQ.png" /></figure><p><a href="https://dotfair.io/">.FAIR</a> is your day-to-day greenops partner, helping you to follow all your cloud carbon footprint in real time. The key features of <a href="https://dotfair.io/">.FAIR</a> are:</p><ul><li><strong>Forecasting</strong>: <a href="https://dotfair.io/">.FAIR</a> provides you a forecast of your carbon footprint.</li><li><strong>Supports multiple cloud providers</strong>: <a href="https://dotfair.io/">.FAIR</a> can gather data from multiple cloud providers.</li><li><strong>Supports multi-tenancy</strong>: <a href="https://dotfair.io/">.FAIR</a> allows you to share your data within and outside your team.</li><li><strong>Carbon reporting</strong>: <a href="https://dotfair.io/">.FAIR</a> has a simple and intuitive interface, you can create carbon footprint reports in minutes.</li><li><strong>Developer friendly</strong>: <a href="https://dotfair.io/">.FAIR</a> has an API, you can integrate it with your own tools.</li></ul><p>Thanks to it you can easily manage to reduce your cloud carbon footprint thus your billing.</p><p>Moreover, you can set carbon goals to your teams then sensibilize your developers and ops to green IT.</p><h3>Conclusion</h3><p>In this article we saw the environmental challenges that face companies in IT and how to manage to reduce their cloud carbon footprint thanks to <a href="https://dotfair.io/">.FAIR</a>, an innovative tool providing a real time overview of their footprint. At the moment, <a href="https://dotfair.io/">.FAIR</a> is not finished. If you want to know more about feel free to contact us : <strong>contact@dotfair.io</strong></p><p>I hope you enjoyed this article. If you have any questions, feel free to ask them in the comments or check out my other articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0fe9708cf3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dotfair/simply-reduce-your-cloud-carbon-footprint-f0fe9708cf3f">Simply reduce your cloud carbon footprint</a> was originally published in <a href="https://medium.com/dotfair">Dotfair</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleash the power of error in Go]]></title>
            <link>https://medium.com/@mjoffre/unleash-the-power-of-error-in-go-42bc3fa76cc1?source=rss-83556ffe3621------2</link>
            <guid isPermaLink="false">https://medium.com/p/42bc3fa76cc1</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Mathis Joffre]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 10:02:52 GMT</pubDate>
            <atom:updated>2023-01-03T10:22:45.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v67gPN0nzZ7h7qGW.png" /></figure><p>If you are a Go developer, you must have encountered errors in Go but do you know how powerful they are ? In this article, we will discuss the error handling in Go and how to use it in your code.</p><h4>What is an error in Go?</h4><p>An error is a type that implements the error interface. The error interface is defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40c17037431bab762eb0df538adda1a4/href">https://medium.com/media/40c17037431bab762eb0df538adda1a4/href</a></iframe><p>The error interface is very simple, it has only one method, Error(). This method returns a string. The string returned by the error interface is the error message.</p><h4>How to handle errors in Go?</h4><p>There are many ways to handle errors in Go. The most common way is to use the if statement. Let’s take an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1924f147fb8bd2c08065612b27d64dda/href">https://medium.com/media/1924f147fb8bd2c08065612b27d64dda/href</a></iframe><p>In this example, we open a file. If an error occurs, we print the error and return. If no error occurs, we print the name of the file.<br>The problem is that we don’t know what kind of error occurred. We only know that an error occurred. Maybe this error is not important and we can continue our program. Maybe this error is important and we need to stop our program. We don’t know.<br>Moreover, when reading the code, it is not clear on which error can occur. We have to read the documentation of the os.Open function to know what kind of errors can occur.</p><h4>How to handle errors in Go — Implementations of the error interface</h4><p>Most of the packages in Go have their own error interface implementation. For example, the os package has the os.PathError type. This type is used to represent errors that can occur when opening a file. The os.PathError type is defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b6f64031c7705cd49a9e0c71affb3f1/href">https://medium.com/media/6b6f64031c7705cd49a9e0c71affb3f1/href</a></iframe><p>The os.PathError type has three fields:</p><ul><li>Op: the operation that failed</li><li>Path: the path of the file</li><li>Err: the error that occurred</li></ul><p>All those fields are exported, so we can access them and use them in our code. Let’s take an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b406ffb358c9662abd3bfdcebfbad110/href">https://medium.com/media/b406ffb358c9662abd3bfdcebfbad110/href</a></iframe><p>In this example, we check if the error is a PathError. If it is, we print the path and the error. If it is not, we print the error.<br>This is a very simple example, but it shows how to use the already builtin errors in Go. We can use those types to handle errors properly.</p><h4>How to handle errors in Go — Custom error type</h4><p>Maybe you want to create your own error. You can do it by implementing the error interface. Let’s take an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4395855c46d0a178785cebd9b3625dcc/href">https://medium.com/media/4395855c46d0a178785cebd9b3625dcc/href</a></iframe><p>In this example, we create a MyError type that implements the error interface. The MyError type has one field, msg, that is a string. The Error() method returns the msg field.<br>Moreover, we can create a new error by using the errors.New function. Let’s take an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/673c6e93fa182adc616ce3dc67dc5bb9/href">https://medium.com/media/673c6e93fa182adc616ce3dc67dc5bb9/href</a></iframe><p>Normally this snippet will throw our new error.<br>Now we can use this error in our code. We can check if the error is our error and handle it properly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce1ac8ec224b912dcff0cb5d4bb89422/href">https://medium.com/media/ce1ac8ec224b912dcff0cb5d4bb89422/href</a></iframe><h4>How to handle errors in Go — Wrap errors</h4><p>Sometimes, we want to wrap an error. We can do it by using the errors.Wrap function provided by github.com. Let’s take an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29eda442dccdfc4570f77a6cf0d657b0/href">https://medium.com/media/29eda442dccdfc4570f77a6cf0d657b0/href</a></iframe><p>Plus, wrapping an error will keep the stack trace. This is very useful when debugging.<br>If you don’t want to use the github.com/pkg/errors package, you can use the fmt.Errorf function. Let’s take an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c374c0a5ff4bedc882dfaa3f5bba9292/href">https://medium.com/media/c374c0a5ff4bedc882dfaa3f5bba9292/href</a></iframe><p>The fmt.Errorf function is very similar to the errors.Wrap function. The only difference is that the fmt.Errorf function doesn’t keep the stack trace.</p><h3>Conclusion</h3><p>In this article, we saw how to handle errors in Go. We saw how to use the already builtin errors in Go. We saw how to create our own error. We saw how to wrap an error. We saw how to use the errors.Wrap function. We saw how to use the fmt.Errorf function.<br>I hope you enjoyed this article. If you have any questions, feel free to ask them in the comments. If you want to learn more about Go, you can check out my other articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42bc3fa76cc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go API authorization made simple]]></title>
            <link>https://medium.com/@mjoffre/go-api-authorization-made-simple-9ee65d23a2b3?source=rss-83556ffe3621------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ee65d23a2b3</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[open-policy-agent]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mathis Joffre]]></dc:creator>
            <pubDate>Sun, 01 Jan 2023 18:58:10 GMT</pubDate>
            <atom:updated>2023-01-01T19:48:32.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AaYXMbz8ZPlyXfb6.png" /></figure><p>Most of the time, you want to authorize your users before they can access your API. This is a very common task and it is very easy to do with Go. In this article, we will see how to do it.</p><h4>The problem</h4><p>Let’s say you have an API that you want to protect. You want to make sure that only authenticated users can access it. You also want to make sure that the user has the right permissions to access the API.</p><p>For example, grant access to premium contents only to premium users.</p><h4>The solution</h4><p>To solve this problem, we must introduce two concepts: authentication and authorization. Authentication is the process of verifying that a user is who they say they are. Authorization is the process of verifying that a user has the right permissions to access a resource.</p><p>In this article, we will see how to do only the authorization part. We will see how to verify that a user has the right permissions to access a resource.</p><p>Before we start, let’s introduce a few tools that we will use in this article.</p><h3>Tools</h3><h4>Open Policy Agent</h4><p>In this tutorial, we will use <a href="https://www.openpolicyagent.org/">Open Policy Agent</a> (OPA) to solve this problem. OPA is an open source project that provides a policy engine. It can be used to enforce policies in your application. It can be used to authorize your users, validate your data, and much more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*WRXobwrvF8QCiE6e.png" /><figcaption>OPA architecture schema</figcaption></figure><p>I know that you can directly do this inside your app, but the maintainability of your software could be impacted. Imagine, you create a new role inside your organization, you will have to modify your code in order to handle this addition. By using OPA, policies are global to the organization and changes doesn’t force you to modify your code.</p><h4>Opa-middleware library</h4><p>We will use the <a href="https://github.com/Joffref/opa-middleware">opa-middleware</a> library to integrate OPA with our Go application. This library provides a middleware that you can use to authorize your users. It is very easy to use and it is very flexible.</p><h3>Example</h3><p>Let’s assume, your API has two users. Alice who is an article consumer (read access) and Bob who is a publisher (write access)</p><p>We assume that you want to protect the following CRUD endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a7e847c2000af4f280865472fc5c94d/href">https://medium.com/media/8a7e847c2000af4f280865472fc5c94d/href</a></iframe><h4>The OPA policy</h4><p>The OPA policy is a JSON document that defines the permissions of your users. It is very easy to write. You can write it in a few minutes.</p><p>In this example, we will use the following data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7f8b64564470593405e2c7e4e61a20e/href">https://medium.com/media/f7f8b64564470593405e2c7e4e61a20e/href</a></iframe><p>This data defines two users: `alice` and `bob`. `alice` has the `articles:read` permission. `bob` has the `articles:read` and `articles:write` permissions.</p><p>The following policy will be used in this example to authorize the users:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dd2c4696e89115ec174c9a8748cd504/href">https://medium.com/media/0dd2c4696e89115ec174c9a8748cd504/href</a></iframe><h4>The Go application</h4><p>Now that we have the OPA policy, we can write our Go application. We will use the <a href="https://github.com/Joffref/opa-middleware">opa-middleware</a> library to integrate OPA with our application.</p><h4>Embedded</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/934470bbbe30704e6c1aa9a8e4c4df35/href">https://medium.com/media/934470bbbe30704e6c1aa9a8e4c4df35/href</a></iframe><h4>Remote</h4><p>Or, if you want to use OPA as a sidecar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb1d430f49466e0bb4cfd42e463a683a/href">https://medium.com/media/eb1d430f49466e0bb4cfd42e463a683a/href</a></iframe><h3>Let’s test it</h3><p>First, try to get articles with Alice account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*NgezHjtHKixSyrV_KuMKuA.png" /></figure><p>It works indeed in OPA Alice is authorized to read articles. Now, let’s see if Alice can create an article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*FZ9pnYXSrrVOcxcMw50iCg.png" /></figure><p>As shown, Alice can’t create an article, as it’s explicitly written in rules. Let’s see with Bob.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*u6FOo1AK8Z7UtSySoVuIJA.png" /></figure><p>Bob can create an article. Authorizations are well enforced in the articles endpoint of our API.</p><p>Thanks for reading !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ee65d23a2b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>