<?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 Ousama Esbel on Medium]]></title>
        <description><![CDATA[Stories by Ousama Esbel on Medium]]></description>
        <link>https://medium.com/@ousama.esbel?source=rss-2c7c3c47e246------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*h5tZrwqy4nJ871tV.</url>
            <title>Stories by Ousama Esbel on Medium</title>
            <link>https://medium.com/@ousama.esbel?source=rss-2c7c3c47e246------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:24:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ousama.esbel/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[Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 4]]></title>
            <link>https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-4-31988816cab1?source=rss-2c7c3c47e246------2</link>
            <guid isPermaLink="false">https://medium.com/p/31988816cab1</guid>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Tue, 20 Apr 2021 09:33:12 GMT</pubDate>
            <atom:updated>2021-08-26T19:21:27.038Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/1bf09984b6ee?source=post_stats_page-------------------------------------">Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part </a>4</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UbtvCPSuGn0xkfjqyFphUQ.jpeg" /></figure><p>Kubernetes has become the de facto container orchestrator due to its various functionalities and flexibility. Although Kubernetes documentation is thorough and provides many examples, it is not straight forward to combine all these tutorials and use it to deploy a real-life application with several services from end-to-end. With that, I will demonstrate how to deploy a real-life scenario application on Azure Kubernetes Cluster (AKS) as the production platform. Moreover, I will be discussing day 1 and day 2 operations of the application life cycle in Kubernetes in series of articles. Here are the main headlines:</p><ul><li>Discuss the application and set up the cluster, container registry and the production namespace. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>)</li><li>Deploy Config Maps, Secrets and Persistent Volumes. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">part 2</a>)</li><li>Deploy, monitor and define update strategies for the services including setting up Traefik as Ingress Controller. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">part 3</a>)</li><li>DevOps and Auto deployment using Github Action. (part 4)</li></ul><p>You don’t have to use Azure Kubernetes Service per say, you can easily re-configure the manifests to be compatible to any Kubernetes installation, such as AWS EKS or Linode. However, as a prerequisite, you need to have a basic knowledge of Kubernetes, Docker, yaml, shell scripting and Github Actions. In addition, if you want to run the application along with the tutorial, you need to:</p><ul><li>Clone the <a href="https://github.com/uzi0espil/cookiecutter-django-k8s">Cookiecutter-django-k8s</a> repository.</li><li>Install Docker and Docker-compose.</li><li>Enable or install <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">Kubectl</a>.</li><li>Install <a href="https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest">Azure cli</a>.</li></ul><p>In this article, best practices for continuously deploying an application in Kubernetes cluster is discussed. Then, a demonstration is provided on how to implement a Continuous Deployment pipeline for the presented application in <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a> using Github and Azure Actions.</p><h3>Continuous Deployment</h3><p>A key benefit of implementing a Continuous Deployment (CD) pipeline is to automate the release of the software in an efficient, fast and trackable way. In theory, Kubernetes makes CD easy to implement due to its declarative nature. Moreover, you describe the state that you want the applications to be. Then, Kubernetes attempts to reach that state. However, as we saw from the previous articles, Kubernetes takes care of the complete infrastructure; starting from setting up the applications’ configurations, jobs and disks to deploying the applications themselves. Monitoring the changes of these different components and automate the CD become very challenging. In other words, the more different Kubernetes resources you use, the harder it is to automate the complete pipeline.</p><p>Let’s briefly describe how ideally we can implement CD pipeline for the main Kubernetes resources used in the previous articles:</p><h4>ConfigMaps and Secrets</h4><p>In some cases, you end up updating only the application’s configurations, i.e. ConfigMaps and Secrets, without updating the microservices themselves. When CD is ran, the configuration changes are not reflected in the microservices unless you restart the microservices that are using them. This happens because microservices and configurations have different lifecycles and constraints.</p><p>One way to solve this issue is within the logic of CD pipeline. Moreover, we look for changed configuration manifests: if there is any, we will force restart the microservices that are using these configurations unless these microservices are modified anyway. You can simply check whether a configuration is modified or not by using the option --dry-run that will inform you the output of the command without actually applying the changes. Another method is to check if the last changed files in the repository contains any ConfigMaps/Secrets manifests using for example <a href="https://github.com/tj-actions/verify-changed-files">verify-changed-files</a> Action in your Github Actions workflow.</p><p>Although the idea is simple, the implementation is complicated and error-prone especially when a configuration is used by multiple applications across multiple teams. A better practice is to treat each configuration file as immutable file where you need to create a new version of the ConfigMap/Secret if you want to change its values. With that, you will need to modify the microservices manifests to load or mount the configurations of the newer versions. This gives you the possibility to let other applications that depend on the same configuration to use the current version of the configurations. This approach is followed by <a href="https://spinnaker.io/guides/user/kubernetes-v2/best-practices/#version-your-configmaps-and-secrets">Spinnaker.io</a>.</p><h4>Persistent Volumes</h4><p>In Persistent Volumes, one normally wants to expand the size of an already created volume. This can be easily achieved by modifying the Persistent Volume Claim (PVC). Specifically, the resources.requests.storage attribute. Unlike ConfigMaps/Secrets, updating the PVC will be reflected directly without requiring us to restart the related microservices.</p><p>However, if any of the volume type or class storage are required to be changed, then it is very difficult to handle. In this case, a good practice is to re-create the related microservices again with the new version of the PVC, this approach can be better managed using Infrastructure as Code (IaC) tools such as <a href="https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/persistent_volume">Terraform</a>. IaC tools require different handling in CD that is out of the scope of this article.</p><h4>Microservices</h4><p>The microservices that define the applications are the most common resources to be updated. Essentially, we would like to reflect the changes and the new features in production whenever we make a release. This can be easily done by compiling new docker images that contain the latest code and push these images to a container registry. These images are usually tagged with the release version. Then in CD pipeline, the services are forced to be updated by pulling the images from the container registry with the correct tag. Normally, the services are updated along with their correspondent Kubernetes Service.</p><p>The update strategy is defined using rolling update configurations and health check probes that have been explained in <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">part 3</a>. Additionally, we can define further update strategies in the CD pipeline such as Canary strategy or Blue-Green Strategy which I will demonstrate how later. If you are unfamiliar with these mentioned strategies and you would like to learn more, then please refer to this thorough <a href="https://harness.io/blog/continuous-verification/blue-green-canary-deployment-strategies/#:~:text=A%20canary%20deployment%20is%20a,%2C%2075%25%2C%20100%25).">tutorial</a>.</p><h3>Demonstration</h3><p>Let’s demonstrate the CD pipeline using the same example repository and Kubernetes cluster from the previous articles. The repository’s complete CI/CD pipeline is split into three different stages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*NMtjPC_Q26ABRAchI0cs9Q.png" /><figcaption>Three Stages of CI/CD</figcaption></figure><p>In a nutshell, the pipeline starts when a pull-request is submitted, the code style will be linted and tests will be ran. Once merged to master, docker images will be compiled and pushed to the specified container registry. Finally, upon release, we tag the compiled images from the last step with the release version and update the Kubernetes production cluster. Each stage is split into different Github Action scripts in the <a href="https://github.com/uzi0espil/cookiecutter-django-k8s/tree/master/.github/workflows">repository</a>. In this article, I will only discuss the last two stages that are related to CD as the CI stage was already provided by <a href="https://cookiecutter-django.readthedocs.io/en/latest/index.html">Django Cookiecutter</a>.</p><h4>Environment Variables and Secrets</h4><p>Before we start with Github Action scripts, we need to provide Github the necessary environment variables and secrets that are required to run the pipeline. Mainly we need to set:</p><ul><li>Azure’s access information.</li><li>AKS cluster and Resource-Group names.</li><li>Azure Container Registry (ACR) credentials.</li></ul><p>In Github, we can set the environment variables as secrets in settings -&gt; secrets. However, it is good practice to group secrets that are related to an <a href="https://docs.github.com/en/actions/reference/environments">environment</a> in Github, this helps us in the following:</p><ul><li>Assigning different people in the team for different stage of the application’s lifecycle. For example, allow specific members to create a release.</li><li>Re-use the jobs in Github Actions and only change the environment. In most cases, deploying Kubernetes to staging cluster is the same for production cluster. the difference resides in the access and credentials information. With that, we can make the job general and specify to run it on different environments.</li></ul><p>With that, first we create an environment called productionand assign the following keys to it:</p><ul><li>AZURE_ACCESS_INFO</li><li>CLUSTER_NAME</li><li>RESOURCE_GROUP</li></ul><p>AZURE_ACCESS_INFO can be retrieved by running the following command in Azure cli (you only need to run this command once):</p><pre>az ad sp create-for-rbac --name &quot;aksaccess&quot; --role contributor --scopes /subscriptions/&lt;SUBSCRIPTION_ID&gt;/resourceGroups/&lt;RESOURCE_GROUP&gt; --sdk-auth</pre><p>The command will return a JSON object that you can copy and store as the value of the AZURE_ACCESS_INFO variable. The other two secrets are self-explanatory and you should have obtained them when you created the cluster (for further information check <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>).</p><p>Environment variables and secrets that are unrelated to any environment can be stored in the general Github Secrets. For example, the container registry information are mostly shared between production and staging environments and therefore unrelated to a specific environment. With that, navigate to settings -&gt; secrets and add the following variables:</p><ul><li>CR_URL</li><li>REGISTRY_USERNAME</li><li>REGISTRY_PASSWORD</li></ul><p>You can find these information in ACR dashboard in Azure’s portal under Access Keys tab. (For further information refer to <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>).</p><h4>Github Action Workflow</h4><p>Let’s start first by compiling and pushing the images to ACR. Here are the main steps to be followed:</p><ol><li>Checkout the code.</li><li>Login to Azure docker.</li><li>Build the docker images locally.</li><li>Iterate through all images in docker-compose file and push each image.</li></ol><p>The following snippet shows how to implement the steps in Github Actions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e086748f15f8fce3b52cfee8afe6ba78/href">https://medium.com/media/e086748f15f8fce3b52cfee8afe6ba78/href</a></iframe><p>First of all, The job, push, is only triggered when a commit is pushed to the master branch as stated in line 1 to 4. The steps are straightforward. However, the final step in line 18, is ran within shell script named push-images.sh. The following snippet shows the shell script’s implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78ad3bb21318ce6ef66495cb223b330c/href">https://medium.com/media/78ad3bb21318ce6ef66495cb223b330c/href</a></iframe><p>Basically, the shell script accepts an argument to set the images tag, if no argument is passed, then latest is chosen. Afterwards, it gets the configuration from the docker-compose file, production.yml, and only tries to find image attribute. Finally, it loops through all images and for each image, it tags the image and pushes it to the container registry.</p><p>Once we have a stable version of our application, we create a release. Beside production release, a release can be alpha, beta or a release candidate (rc*). Normally, you would like to trigger different environment for each release type. In this simple example, only production release is considered which normally starts with v*. like for example, v1.0.0. With that, we trigger the CD pipeline when a release is made that starts with v* as shown in the snippet below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5028ea57e2bb7c145fc31ee3ffe5e81c/href">https://medium.com/media/5028ea57e2bb7c145fc31ee3ffe5e81c/href</a></iframe><p>Then, we need to tag the compiled images with the release version. The following snippet illustrates Github Action script for tagging and versioning the docker images:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1bbf35ddc6ec316b6a1c46fd8a6cfca/href">https://medium.com/media/e1bbf35ddc6ec316b6a1c46fd8a6cfca/href</a></iframe><p>The steps are very similar to the previous job, push , the only difference is that we pass a parameter to push-images.sh script. The parameter is defined in the Get Release Version in line 16, where we retrieve the release version from Github’s internal environment variable, GITHUB_REF . Finally, for performance purposes, we pull the latest images that are built from the previous stage instead of re-building them again.</p><p>Once the job is done, we can deploy the changes to AKS’s Cluster. Here are the steps that are required to deploy to AKS:</p><ol><li>Checkout the new code.</li><li>Login to AKS.</li><li>Get release version</li><li>Get list of Kubernetes manifests.</li><li>Get list of images.</li><li>Deploy to cluster.</li></ol><p>The following snippet illustrates how the steps are implemented:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3118318a1b3c8f7cb9f2d19422ca3bef/href">https://medium.com/media/3118318a1b3c8f7cb9f2d19422ca3bef/href</a></iframe><p>First of all, in line 3, we define that this job runs with respect to production environment that we created earlier. In step 2, Azure’s action <a href="https://github.com/Azure/k8s-set-context/tree/releases/v1">aks-set-context</a> is used to programmatically<strong> </strong>login to AKS, the action depends on the secrets we defined in production environment. In addition, Azure action <a href="https://github.com/Azure/k8s-deploy/">k8s-deploy</a> in line 33 is used to deploy to cluster. It expects list of manifests to run, the new compiled images’ URLs and the targeted Kubernetes Namespace within our cluster. The list of manifests are retrieved in step 4 using shell script list-manifests.sh . The script simply loops through the Kubernetes folders and gets the path to each manifest. Here is the how list-manifests.sh is implemented:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7b3203895c7bc75d0cae40aa4b20a40/href">https://medium.com/media/a7b3203895c7bc75d0cae40aa4b20a40/href</a></iframe><p>The order of the manifests is important, as you want to apply changes of ConfigMaps and Secrets first before you update the microservices.</p><p>Finally, the list of images are retrieved using list-images.sh that is very similar to push-images.sh except it only gets the images URLs without pushing them to ACR.</p><p><a href="https://github.com/Azure/k8s-deploy/">k8s-deploy</a> can take further argument to define the deployment strategy, it accepts both Canary and Blue-Green strategies. For that, you are required to provide additional variables for Canary strategy such as the percentage of replicas of baseline and canary variants. However, you don’t need to modify your Kubernetes infrastructure or introduce additional resources.</p><p>Finally, if you didn’t link the AKS cluster with ACR when you created the AKS cluster (as we did in <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>), then you will be required to provide the access to ACR through parameter in k8s-deploy action. Further information can be found in this <a href="https://docs.microsoft.com/en-us/azure/container-registry/container-registry-auth-kubernetes">tutorial</a>.</p><p>With that, we have a CD pipeline using Github Actions to roll updates of the newly released features to the production Kubernetes cluster.</p><h3>Things To Consider</h3><ul><li>Use <a href="https://helm.sh/">Helm</a> to automate the deployment of Kubernetes and make the manifests more customizable.</li><li>Use <a href="https://www.terraform.io/">Terraform </a>to automate the infrastructure changes.</li></ul><h3>Clean Up</h3><p>If you ran the tutorial, please go ahead and delete the resource group, Azure then will delete every resource in that group. Additionally, delete the service principal that has been created along with the resource group.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31988816cab1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-4-31988816cab1">Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 4</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 3]]></title>
            <link>https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee?source=rss-2c7c3c47e246------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bf09984b6ee</guid>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[traefik]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 07:33:37 GMT</pubDate>
            <atom:updated>2021-08-26T19:20:59.988Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UbtvCPSuGn0xkfjqyFphUQ.jpeg" /></figure><p>Kubernetes has become the de facto container orchestrator due to its various functionalities and flexibility. Although Kubernetes documentation is thorough and provides many examples, it is not straight forward to combine all these tutorials and use it to deploy a real-life application with several services from end-to-end. With that, I will demonstrate how to deploy a real-scenario application on Azure Kubernetes Cluster (AKS) as the production platform. Moreover, I will be discussing day 1 and day 2 operations of the application lifecycle in Kubernetes in series of articles. Here are the main headlines:</p><ul><li>Discuss the application and set up the cluster, container registry and the production namespace. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>)</li><li>Deploy Config Maps, Secrets and Persistent Volumes. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">part 2</a>)</li><li>Deploy, monitor and define update strategies for the services including setting up Traefik as Ingress Controller. (part 3)</li><li>DevOps and Auto deployment using Github Action. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-4-31988816cab1">part 4</a>)</li></ul><p>You don’t have to use Azure Kubernetes Service per say, you can easily re-configure the manifests to be compatible to any Kubernetes installation, such as AWS EKS or Linode. However, as a prerequisite, you need to have a basic knowledge of Kubernetes, Docker, yaml and shell scripting. In addition, if you want to run the application along with the tutorial, you need to:</p><ul><li>Follow the previous tutorials (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a> and <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">part 2</a>)</li><li>Clone the <a href="https://github.com/uzi0espil/cookiecutter-django-k8s">Cookiecutter-django-k8s</a> repository.</li><li>Install Docker and Docker-compose.</li><li>Enable or install <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">Kubectl</a>.</li><li>Install <a href="https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest">Azure cli</a>.</li></ul><p>In this article, the application is launched, where Django and Flower will be exposed to external traffic using LoadBalancer and Traefik Controller. Moreover, both endpoints are secured using TLS certificates that are automatically generated from Traefik. To conclude, day 2 operations are discussed, mainly rolling updates and health checks.</p><h3>Deploy Services</h3><p>In this application, there are five different services. All these services are interconnected together through internal network. Hence, each should have an internal IP address. However, two of them should be also accessible from outside, namely Django and Flower services.</p><p>All services will be created as Deployments except Postgres where it will be created as a StatefulSet. The Kubernetes manifests of these services look really similar, the manifests should address the following points:</p><ul><li>Path to the image that we pushed to ACR.</li><li>Ports that the application is using.</li><li>The environment variables and secrets.</li><li>Attached volumes and where to mount.</li><li>Kubernetes Service to define the policy on how to access the Pod whether internally or externally.</li></ul><p>Let’s see how the above points are defined for Django service:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c65b13354405c85d8356f55a0fddfad/href">https://medium.com/media/5c65b13354405c85d8356f55a0fddfad/href</a></iframe><p>Django’s container image is defined in line 21. Unlike Docker, you cannot use environment variables within the manifests. Therefore, you need to go to each manifest in compose/kubernetes/*.yaml and change the image URL to match with your ACR. This shortcoming can be addressed by Helm. However, this is a topic for a different day.</p><p>Regarding the port, Django is served using Gunicorn where the port is defined in compose/production/django/start. With that, we need to expose port 5000.</p><p>Then, we define the environment variables and secrets. In the manifests, we refer to the ConfigMaps and Secrets that we created in the earlier section. Additionally, we add two environment variables that expand on the variables defined in the ConfigMaps.</p><p>Next is the volumes’ section, at line 61, where we define what Volume Persistent Claims (VPCs) the pod needs to use (VPCs are created in <a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">part 2</a>) and, on line 41, we define where the attached volume should be mounted in the Pod. In our case, we want to mount it as Django’s media folder.</p><p>Finally, we configure the service policy which should be defined as a different Kubernetes resource. In Django’s case, we want to expose it to the other services and map port 5000 in the pod to port 80 of the Service. Of course, this is not ideal for production as we want to use TLS for our application. But let’s make this work as a first step and, later, we will modify it, replace the service with Ingress Resource and use TLS.</p><p>To deploy the services, run the following commands:</p><pre>kubectl apply -f compose/kubernetes/.</pre><p>In our examples, the workers are doing the heavy lifting, so it is purposeful to scale the workers. Accordingly, I sat the replicas in celeryworker.yaml to 3. There are additional sections in the celeryworker and Django that I will address in the upcoming section.</p><p>In the first run, the cluster will take some time to pull the images from the ACR. After some time, you should have the following results when running kubectl get pods -n production -o wide</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uc7CMQymc1MH3zs26ztfEg.png" /><figcaption>Deployed services.</figcaption></figure><h3>Traefik as Ingress Controller</h3><p>One of the main strength of Kubernetes is that it is flexible allowing you to choose any framework for your resources. To connect your cluster to external network, we usually tend to create an Ingress Controller. In AKS, an Ingress Controller can be integrated upon creating the cluster by enabling HTTP external Connection. Azure then will create a Nginx Ingress Controller. Nginx is a very reliable reverse-proxy framework. However, it falls short in several aspects:</p><ul><li>Difficult to integrate it in Kubernetes cluster.</li><li>Static configuration for each service in the cluster which makes it hard to manage in a cluster that is frequently changing.</li><li>Doesn’t support assigning TLS certificates out of the box. It requires another resource to manage certification like <a href="https://cert-manager.io/docs/">Cert-Manager</a>.</li></ul><p>Although Azure takes all the heavy lifting integrating Nginx in our cluster, it still doesn’t solve the other shortcomings. That is why I propose using Traefik. Traefik is a modern reverse-proxy that has been first released in the age of containers. Furthermore, it is easier to integrate as it speaks to Kubernetes natively and doesn’t need an extra wrapper to speak with Kubernetes. In addition, Traefik has built-in Let’s Encrypt and fully supports TCP.</p><p>There are three different strategies to integrate Traefik:</p><ul><li>Use Kubernetes Ingress resource to define the paths. This requires Traefik controller to have the correct permissions to watch ingress API and cannot automatically generate TLS certificates for your services. It requires handing over TLS certificates manually or by using another service like Cert-Manager [<a href="https://doc.traefik.io/traefik/v1.7/user-guide/kubernetes/">tutorial</a>].</li><li>Use Traefik custom Kubernetes resources that allow us to specify Ingresses with Traefik configuration and establish TLS certificates from Let’s Encrypt. In addition, it also requires Traefik controller to have the permissions to watch the new resources [<a href="https://doc.traefik.io/traefik/providers/kubernetes-crd/">tutorial</a>].</li><li>Provide Traefik the complete configuration from a ConfigMap without the need to define Kubernetes Ingress resource. In the configuration, you can define any middleware and you can establish TLS certificates.</li></ul><p>The first two strategies are complicated to integrate. However, they provide the needed flexibility. For applications that have few access points for which the Ingresses are not frequently changed such as in our case, then it is easier and less error-prone to go for the third option.</p><p>Without further ado, first, we need to create a LoadBalancer service for the Traefik controller. The service manifest can be described as the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440d5f42a45760aeabeffbe7247ad470/href">https://medium.com/media/440d5f42a45760aeabeffbe7247ad470/href</a></iframe><p>In a nutshell, we are asking AKS for an external IP address and accept connections on ports 80, 443 and 5555.</p><p>To create the service, run the following command:</p><pre>kubectl create -f ingress/traefik-svc.yaml</pre><p>To retrieve the external IP address, find traefik when running the following command:</p><pre>kubectl get services -n production</pre><p>Then, map the external IP address to a domain. If you don’t already have a domain, you can use Azure’s <a href="https://docs.microsoft.com/en-us/azure/app-service/manage-custom-dns-buy-domain">App Service Domain</a> to create a domain name. It takes some time for the DNS to be updated. Meanwhile, let’s work on Traefik configurations. Traefik requires two configurations:</p><ul><li><strong>acme.json</strong>: required for automatic certificate generation.</li><li><strong>traefik.yml</strong>: contains all the configurations such as entrypoints, middleware, services and routes.</li></ul><p>Here is the manifest for both ConfigMaps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/781df88879610fbc5a684ef70ba8550d/href">https://medium.com/media/781df88879610fbc5a684ef70ba8550d/href</a></iframe><p>First of all, replace&lt;your-URL&gt; with the domain name you mapped to the external IP address and replace &lt;your-email&gt; with your email. In the manifest, we are creating two ConfigMaps. The first one is acme.json which is simply an empty string. It is really crucial for Traefik to have this file available in order to generate the certificates, even if it is empty. The second ConfigMap is traefik.yml In line 31, we are specifying that we are using Let’s Encrypt for generating TLS certificates and store the needed information in the acme.json file that we should create. In line 41, the routes to the application are defined. Moreover, services, entrypoints and middlewares are specified. For example, Django service requires Traefik to redirect any requests to HTTPs and allow CSRF headers. The following commands create Traefik’s ConfigMaps:</p><pre>kubectl create -f configmaps/traefik-acme.yaml<br>kubectl create -f configmaps/traefik-config.yaml</pre><p>Now, it is time to create Traefik controller. There are two recommended ways to deploy Traefik pod, either as Kubernetes Deployment or DaemonSet. This official <a href="https://doc.traefik.io/traefik/v1.7/user-guide/kubernetes/#deploy-traefik-using-a-deployment-or-daemonset">article</a> by Traefik explains the difference between them and when to use each. In any case, Deployment is used in this tutorial, however it is fairly easy to swap back and forth between them. Here is the Traefik Deployment manifest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc40fa3b35225f2e0c044e03d14a46f5/href">https://medium.com/media/bc40fa3b35225f2e0c044e03d14a46f5/href</a></iframe><p>In the manifest, we are starting the pod by running traefik command with arguments specified in line 25. What is important to note is that Traefik will look at the configuration file in path /etc/traefik/traefik.yml. So we need to mount the configuration file there.</p><p>At line 30, several ConfigMaps are projected into the same directory to be passed to the pod as a volume. Moreover, traefik.yml configuration is added to the top of the directory specified in the mounted path. However, acme.json is mounted on acme folder with access mode 0600. The complete directory is then mounted within the pod in the specified path in volumeMounts.mountPath as shown at line 23. And that’s it!</p><p>To create Traefik controller, run the following command:</p><pre>kubectl create -f compose/kubernetes/ingress/traefik-controller.yaml</pre><p>Once Traefik is up, you can navigate to your domain, you will be redirected to HTTPs and can access the website normally.</p><h3>Rolling Update and Health Checks</h3><p>The ability to update your application with zero-downtime is a key feature that Kubernetes offers. The update happens progressively. For example, in deployments, a new ReplicaSet is created where it contains the updated version. At the same time, the old ReplicaSet still exists. Then, a new pod is created in the new ReplicaSet to replace a pod from the old ReplicaSet. This is done incrementally until all pods in the old ReplicaSet are replaced. The update strategy is controlled by the following settings:</p><ul><li><strong>maxUnavailable</strong>: How many resources we can maximum take out from current replicas.</li><li><strong>maxSurge</strong>: How many additional resources we can add to the existing replicas.</li></ul><p>In our application, we need to make sure that we have at least three workers up and running at all times, even during updates. In that case, we can set maxUnavailable and maxSurge to 0 and 1 respectively. With that, one pod is added at a time, and that there will always be 3 pods ready to service in the deployment. The following figure illustrates what happens on every step:</p><figure><a href="https://www.bluematador.com/blog/kubernetes-deployments-rolling-update-configuration"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qlew6fhK_HAiCIsMKocMaQ.gif" /></a><figcaption>Rolling Update one pod at a time. Image is taken from <a href="https://www.bluematador.com/blog/kubernetes-deployments-rolling-update-configuration">here</a></figcaption></figure><p>As illustrated, once the new version is in “Ready” state, a pod from the old ReplicaSet is terminated. But isn’t “Ready” different from one service to another? For instance, in case of a web server, the service is ready when it can receive HTTP requests, on the other hand, databases are said to be ready when they can accept TCP connection to their open port. Therefore, Kubernetes allows us to define how each service is ready.</p><p>In Celery, we can identify the health of its worker and check if it is ready by running the following command:</p><pre>celery inspect ping -A config.celery_app -d celery@$HOSTNAME</pre><p>With the above command, we need the pod to warm up for 30 seconds and then try to run the command every minute until it gets at least 1 successful result (i.e., exit with code 0). With this configuration, ideally, the worker will need 30 seconds to be ready and with 90 seconds we would have replaced the three workers. Even if it is good enough for our application, it might be too long for some other cases. We can translate the above requirements in Kubernetes as the following:</p><pre>readinessProbe:<br>  exec:<br>    command: <br>      - bash<br>      - -c<br>      - celery inspect ping -A config.celery_app -d celery@$HOSTNAME<br>  initialDelaySeconds: 30<br>  periodSeconds: 20<br>  successThreshold: 10</pre><p>What about the terminated Celeryworker? What happens if the worker is performing a task when the Kubernetes decided to terminate it? Shouldn’t it wait until the worker finishes its task and then shut it down? To deal with this, Kubernetes sends a SIGTERM signal to the container and waits a period of time (default 30 seconds) until the container gracefully shuts down. If the container doesn’t terminate within the specified period, Kubernetes will force it to shut down using SIGKILL signal.</p><p>Luckily, Celery provides the <a href="https://docs.celeryproject.org/en/stable/userguide/workers.html#stopping-the-worker">desired functionality</a> out of the box. Furthermore, it will make sure that Celeryworker finishes all currently executed tasks once it receives SIGTERM. However, we still need to increase the waiting period to a suitable time that would let the worker finish its task. We control the time by configuring spec.termplate.spec.terminationGracePeriodSeconds in the deployment’s manifest.</p><p>Finally, to complete the lifecycle of our app, we need to continuously monitor our app to make sure that it is running correctly at all times. In Kubernetes, this is done by defining health checks <em>probes </em>that act on containers<em>. </em>Moreover, Kubernetes can take actions on containers that fail the health check.</p><p>The Readiness probe that we used above is one kind of Health check probes. It informs kubelet agent in the node when a container is “ready” to serve a traffic. If it fails, it will be taken out of service. Another crucial probe is the liveness probe which periodically checks if a container is dead or still alive. If the liveness probe fails, the container will be killed and what happens next depends on the restart policy we specified in the service’s manifest.</p><p>For a web server that has to talk to a database, such the case for Django service, we need to separate the readiness and liveness probes. The convention is that if the website is up but the database is down or unreachable, the liveness should pass but the readiness fails. The reason behind this design is that we don’t want to keep restarting the website for another service’s fault. What we need is to take the website out of service until the problem is resolved.</p><p>With that, a middleware has been implemented in Django to expose two endpoints, one for liveness and another for readiness, the liveness endpoint will check the status of Django before getting to the point where Django checks the database connection. In this present case, the readiness endpoint checks every external connection that Django makes. For more details check out this <a href="https://www.ianlewis.org/en/kubernetes-health-checks-django">article</a>. The liveness and readiness specifications for Django service are listed below:</p><pre>restartPolicy: always<br>...<br>livenessProbe:<br>  httpGet:<br>    path: /healthy<br>    port: 5000  # Gunicorn port<br>  initialDelaySeconds: 30<br>  periodSeconds: 31<br>  timeoutSeconds: 2<br>  failureThreshold: 2<br>readinessProbe:<br>  httpGet:<br>    path: /readiness<br>    port: 5000  # Gunicorn port <br>  initialDelaySeconds: 30<br>  periodSeconds: 37<br>  timeoutSeconds: 5<br>  failureThreshold: 2</pre><p>Django service will be given 30 seconds to start up. Then, every 31 seconds a http GET request will be sent to the healthy endpoint. If it failed in two consecutive times, Django will be marked as failure. In return, it will be terminated and a new service will be created. It is done similarly for the readiness probe but with different endpoint and configuration.</p><h3>Things To Consider</h3><ul><li>Use <a href="https://helm.sh/">Helm</a> to automate the deployment of Kubernetes and make the manifests more customizable.</li><li>Affinity settings should be specified in Traefik’s Deployment to ensure that two pods don’t end up on the same node.</li><li>Use <a href="https://azure.microsoft.com/en-us/services/postgresql/">Azure Postgres Service</a> instead of hosting your PostgresDB in your Cluster.</li><li>Use Traefik Custom Ingress Resources instead of specifying the configuration using ConfigMaps.</li></ul><h3>Next</h3><p>In the next tutorial, I will discuss how Kubernetes cluster lifecycle is managed using Continuous Deployment pipeline in Github Actions.</p><h3>Clean Up</h3><p>If you ran the tutorial, please go ahead and delete the resource group, Azure then will delete every resource in that group. Additionally, delete the service principal that has been created along with the resource group.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bf09984b6ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 3</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 2]]></title>
            <link>https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f?source=rss-2c7c3c47e246------2</link>
            <guid isPermaLink="false">https://medium.com/p/970f1d82b65f</guid>
            <category><![CDATA[configmap]]></category>
            <category><![CDATA[persistent-volume]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 08:26:19 GMT</pubDate>
            <atom:updated>2021-08-26T19:19:39.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UbtvCPSuGn0xkfjqyFphUQ.jpeg" /></figure><p>Kubernetes has become the de facto container orchestrator due to its various functionalities and flexibility. Although Kubernetes documentation is thorough and provides many examples, it is not straight forward to combine all these tutorials and use it to deploy a real-life application with several services from end-to-end. With that, I will demonstrate how to deploy a real-scenario application on Azure Kubernetes Cluster (AKS) as the production platform. Moreover, I will be discussing day 1 and day 2 operations of the application lifecycle in Kubernetes in series of articles. Here are the main headlines:</p><ul><li>Discuss the application and set up the cluster, container registry and the production namespace. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">part 1</a>)</li><li>Deploy Config Maps, Secrets and Persistent Volumes. (part 2)</li><li>Deploy, monitor and define update strategies for the services including setting up Traefik as Ingress Controller. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">part 3</a>)</li><li>DevOps and Auto deployment using Github Action. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-4-31988816cab1">part 4</a>)</li></ul><p>You don’t have to use Azure Kubernetes Service per say, You can easily re-configure the manifests to be compatible to any Kubernetes installation, such as, AWS EKS or Linode. However, as a prerequisite, you need to have a basic knowledge of Kubernetes, docker, yaml and shell scripting. In addition, if you want to run the application along with the tutorial, you need to:</p><ul><li><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">Follow the previous tutorial</a>.</li><li>Clone the <a href="https://github.com/uzi0espil/cookiecutter-django-k8s">Cookiecutter-django-k8s</a> repository.</li><li>Install Docker and Docker-compose.</li><li>Enable or install <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">Kubectl</a>.</li><li>Install <a href="https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest">Azure cli</a>.</li></ul><p>This article discusses how to manage the application’s environment variables and configurations as well as how to set up the volume profiles that will be mounted onto the containers.</p><h3>ConfigMaps and Secrets</h3><p>Before we start deploying our services, we need to configure the environment variables and secrets that the services need to function properly. So, I have translated all cookiecutter .envs files into ConfigMaps and Secrets. You can add ConfigMaps and Secrets manually to your cluster through Configuration tab in your Azure cluster dashboard. However, it is better to automate these steps through manifests.</p><p>You can find the configuration files in compose/kubernetes/configmaps and secrets . To deploy them in your cluster, run the following commands:</p><pre>kubectl create -f compose/kubernetes/configmaps/.<br>kubectl create -f compose/kubernetes/secrets/.</pre><p>Kubernetes Secret resource is not the best way to store sensitive data as the values are stored as an encoded base64. Instead, we can use Azure’s <a href="https://azure.microsoft.com/en-us/services/key-vault/">Key Vault</a> resource to securely save these configuration and provide them to the services. However, it is more complicated to configure and integrate than Secrets.</p><h3>Persistent Volumes</h3><p>Persistent Volumes (PV) are very crucial resources to make an application stateful. For our application, we need three different volumes:</p><ul><li>Volume for Postgres data.</li><li>Volume for backing up Postgres.</li><li>Shared volume for media directory that contains the uploaded images.</li></ul><p>Kubernetes provides two methods to create and attach PVs, either dynamically or statically. As a developer using Kubernetes, you are only allowed to create volumes based on profiles determined by the cluster administrator. These profiles are called Storage Classes. Out of the box, Azure provides four different types of Storage Classes. However, all these storage classes will not retain your data if the volume is gone. Moreover, you will lose all your data. To tackle this issue, you can do one of the following approaches:</p><ul><li>Create a custom Storage Class and set the reclaim policy to retain the data. Then, you can dynamically create volumes with this class.</li><li>Create a static persistent volume from the default storage class and override the reclaim policy.</li><li>Dynamically create a Persistent Volume and then patch the created volume to retain the data.</li></ul><p>In this tutorial, I will go through all of the above approaches, although the last option is the least favorable because you cannot reproduce it from manifests. Furthermore, here are the different strategies that will be used:</p><ul><li>For the shared media, a static Persistent Volume will be created from <a href="https://kubernetes.io/docs/concepts/storage/storage-classes/#azure-disk">azurefile</a> Storage Class.</li><li>For Postgres data, I will create a custom Storage Class to define Azure disk that can retain information, then create a dynamic Persistent Volume.</li><li>For Postgres backups, I will create a dynamic Persistent Volume from Azure’s default Storage Class and manually modify the Persistent Volume to retain the information.</li></ul><h4>Media Shared Volume</h4><p>In Static Volume Provisioning, we need to create a Persistent Volume that describes the volume characteristics, like resources, access mode, resource size, etc. Then, we need to create a Persistent Volume Claim (PVC) that can be used to attach the service to the PV.</p><p>Being that, we have to create a Azure Storage Account first. So, head to your resource group, click “add” and search for storage account. The form is straight forward, just make sure to remember the storage account name, to set the location the same as the cluster’s location and to keep everything as default (for real production, you might need to enable soft-delete for restoration purposes).</p><p>Once created, click on the storage account and, on the left menu, click on File shares. Click on add “+ File share” and set the name and Quota as you see fit (in my code I named the File shares <em>aksshare</em>).</p><p>Now, we need to create a Persistent Volume manifest that will attach the newly created File storage to our services (namely Django, Celeryworker and Celerybeat). The following snippet shows how to create the resource:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed6d9fe9856abd97211468f008d41918/href">https://medium.com/media/ed6d9fe9856abd97211468f008d41918/href</a></iframe><p>What you need to bear in mind is that the storage class used is <strong>azureFile</strong>. This type requires credentials in order to mount. The credentials are passed to the volume using Secret. In the cloned repository, I have provided an example manifest of the Secret manifest in compose/kubernetes/secrets/pm.yaml.exmaple, where you have to rename it to pm.yaml and fill in the values inside. You can find the values in the dashboard of Azure Storage Account you created. Head to the dashboard, then go to <em>Access Keys</em> on the right menu and click on <em>show keys</em>. You need to copy the <em>storage account name</em> and any of the provided <em>keys</em>.</p><p>Additionally, the volume will be mounted with permission 0777 for owner with ID 200. In the dockerfile of each service, I created a user for running that service and assigned the user an ID of 200.</p><p>To deploy the volume, run the following commands:</p><pre>kubectl create -f compose/kubernetes/secrets/pm.yaml<br>kubectl create -f compose/kubernetes/persistent_volumes/media.yaml</pre><p>To verify if PV and PVC is created, run the following:</p><pre>kubectl get pv -n production<br>kubectl get pvc -n production</pre><p>You should be able to see that PV has been created and the PVC is bounded to it as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*hhILT7mG-9Hgg_waziiMHw.png" /></figure><h4>Postgres Data Volume</h4><p>First of all, we need to create a custom Storage Class that can retain the data. The following snippet shows the configuration needed to create the Storage Class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3c9f87a83da40ad75d233a42acdb1a9/href">https://medium.com/media/f3c9f87a83da40ad75d233a42acdb1a9/href</a></iframe><p>What is important, is to set the reclaim policy to retain. Additionally, allowVolumeExpansion is very useful to expand the volumes on fly. To create the custom Storage Class, we need to run the following command in the persistent_volumes folder:</p><pre>kubectl create -f storage_classes/retain_azure_disk.yaml</pre><p>In dynamic volume provisioning, we don’t need to create PV, we only need to create a PVC that uses the custom storage class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09a57d18112a845f4085bc58a3380e1f/href">https://medium.com/media/09a57d18112a845f4085bc58a3380e1f/href</a></iframe><p>As before, we deploy the PVC using kubectl apply -f postgres-data.yaml</p><h4>Postgres Backups Volume</h4><p>For Postgres Backups, we will dynamically create Persistent Volume. However, we will not use the custom Class Storage created earlier. As mentioned before, in Dynamic Volume Provision, we only create the claim. The PVC is very similar to the PVC we used for Postgres data, the only difference is that we need to set storageClassName to default to use the default Storage Class provided by Azure. When you create the PVC, you will notice that the reclaim policy is <em>delete</em> as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bcGvhmyg5zJOOEhgP5gH0g.png" /></figure><p>We can update the reclaim policy for this resource by using Kubernetes API as following:</p><pre>kubectl patch pv &lt;pv-name&gt; -p &#39;{&quot;spec&quot;:{&quot;persistentVolumeReclaimPolicy&quot;:&quot;Retain&quot;}}&#39;</pre><p>where &lt;pv-name&gt; in the above case is: pvc-65e37164-058b-4698-bd6a-908a953e1e27 . As much convenient this is, it is hard to trace and document. It would therefore be advisable to use manifests over patching.</p><h3>Next</h3><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">In the next tutorial</a>, the microservices will be launched and exposed to outside using Traefik and LoadBalancer. Both Django and Flower will be secured by TLS. In addition, I will discuss day 2 operations, specifically monitoring the services using health checks and strategies to update the application.</p><h3>Further Improvements</h3><ul><li>Use <a href="https://helm.sh/">Helm</a> to automate the deployment of Kubernetes and make the manifests more customizable.</li><li>Integrate <a href="https://azure.microsoft.com/en-us/services/key-vault/">Key Vault</a> instead of Kubernetes Secret resource.</li><li>Use same Virtual Network for Azure Storage Account and Kubernetes Cluster, and enable soft-delete.</li></ul><h3>Clean Up</h3><p>If you ran the tutorial, please go ahead and delete the resource group, Azure then will delete every resource in that group. Additionally, delete the service principal that has been created along with the resource group.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=970f1d82b65f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 2</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 1]]></title>
            <link>https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef?source=rss-2c7c3c47e246------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c5aa7e683ef</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Fri, 26 Feb 2021 17:17:33 GMT</pubDate>
            <atom:updated>2021-08-26T19:16:13.395Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UbtvCPSuGn0xkfjqyFphUQ.jpeg" /></figure><p>Kubernetes has become the de facto container orchestrator due to its various functionalities and flexibility. Although Kubernetes documentation is thorough and provides many examples, it is not straight forward to combine all these tutorials and use it to deploy a real-life application with several services from end-to-end. With that, I will demonstrate how to deploy a real-scenario application on Azure Kubernetes Cluster (AKS) as the production platform. Moreover, I will be discussing day 1 and day 2 operations of the application life cycle in Kubernetes in series of articles. Here are the main headlines:</p><ul><li>Discuss the application and set up the cluster, container registry and the production namespace. (part 1)</li><li>Deploy Config Maps, Secrets and Persistent Volumes. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">part 2</a>)</li><li>Deploy, monitor and define update strategies for the services including setting up Traefik as Ingress Controller. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-3-1bf09984b6ee">part 3</a>)</li><li>DevOps and Auto deployment using Github Action. (<a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-4-31988816cab1">part 4</a>)</li></ul><p>You don’t have to use Azure Kubernetes Service per say, you can easily re-configure the manifests to be compatible to any Kubernetes installation, such as, AWS EKS or Linode. However, as a prerequisite, you need to have a basic knowledge of Kubernetes, docker, yaml and shell scripting. In addition, if you want to run the application along with the tutorial, you need to:</p><ul><li>Clone the <a href="https://github.com/uzi0espil/cookiecutter-django-k8s">Cookiecutter-django-k8s</a> repository.</li><li>Install Docker and Docker-compose.</li><li>Enable or install <a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">Kubectl</a>.</li><li>Install <a href="https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest">Azure cli</a>.</li></ul><p>In this article, the application will be explained. Then, I will setup the production cluster and private container repository.</p><h3>Application Overview</h3><p>The application is a web service developed using Python, specifically using Django framework. Whenever you start a new project, there are many boilerplate integrations need to be done before you start developing the actual application or translate your business model, for instance, you need to prepare the development environment, docker integration, install python libraries, create database, build the continuous integration pipeline, etc... In order to quickly jump-start the development and directly start on developing the application’s logic, I used <a href="https://github.com/pydanny/cookiecutter-django">Cookiecutter Django</a>. If you use Django framework but never heard of Cookiecutter Django then I encourage you to give it a look as it provides various functionalities for all stages out of the box.</p><p>At the time of writing this tutorial, Cookiecutter Django does not provide Kubernetes integration so I extended it and added the necessary Kubernetes manifests to deploy to Azure Kubernetes cluster.</p><p>The web application consists of the following services:</p><ul><li><strong>Django</strong>: Web framework.</li><li><strong>Redis</strong>: Queue Broker for escalating heavy tasks to workers.</li><li><strong>Celeryworker</strong>: Process background tasks.</li><li><strong>Celerybeat</strong>: Process scheduled tasks.</li><li><strong>Postgres</strong>: Database.</li><li><a href="https://flower.readthedocs.io/en/latest/"><strong>Flower</strong></a>: Task monitoring tool for Celery</li></ul><p>I have implemented a simple use case in the application for the purpose of demonstrating the communication and deployment of the services in the cluster. Basically, the Django web app provides a form in the admin panel where a user can upload an image and specify its title and caption. Then, the application will escalate a task to the queue to resize the image. If any of the workers is free, then it will overtake the task, resize the image and store it.</p><p>With that, <strong>Django</strong>, <strong>Postgres</strong>, <strong>Redis </strong>and <strong>celeryworker </strong>need to communicate with each other to save and resize the image. The communication is done as following:</p><ol><li>Upon form submission, <strong>Django </strong>stores the record in the database.</li><li><strong>Django </strong>uploads the image to a shared volume.</li><li><strong>Django </strong>notifies the queue that a new record has been stored in the database with a given ID.</li><li>An unoccupied <strong>celeryworker </strong>check the queue and overtake the task.</li><li><strong>celeryworker </strong>queries the record from database.</li><li><strong>celeryworker </strong>gets the image from the shared volume, resize it and overwrite the image in the shared volume.</li><li><strong>Celeryworker </strong>notifies <strong>Redis </strong>about the result of the task.</li></ol><p>The following graph illustrates the previous steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*TauXCq0_WUjQPJ790o-_8A.png" /><figcaption>Step by step on how resize image task is carried in the application.</figcaption></figure><p>With the aforementioned scenario, we need to use three different communication medium in Kubernetes to perform the task:</p><ul><li>Kubernetes LoadBalancer resource to access the admin panel.</li><li>ClusterIP to communicate between the services and pass the record’s ID.</li><li>Kubernetes shared Persistent Volume to access and process the image.</li></ul><p>We could convert the image to base64 string and pass it through the internal network without the need to use persistent volume. However, this will decrease the performance and add communication overhead. Also, for the sake of learning, it would be great to utilize different Kubernetes resources.</p><p>In development phase, I prefer to develop using docker-compose since Kubernetes is mainly used for production and manages services in multiple nodes, while we develop locally in a single node. However, you still can develop with Kubernetes locally with one node using Docker Desktop or Minikube.</p><p>The specification of the services can be found in local.yml . With that, you can run the application using:</p><pre>docker-compose -f local.yml up --build</pre><h3>Azure Kubernetes Cluster</h3><p>If you don’t have already an Azure account, you can <a href="https://azure.microsoft.com/en-us/free/">create one for free</a>. You will have free credits that should be more than sufficient to run this tutorial.</p><p>In Azure portal, it is better to group the resources of your app in a logical group, this is called Resource Group. Then, within your created group, click add, and search for Kubernetes service. The form is straight forward, just make sure to remember the resource group and cluster name and enable the following:</p><ul><li>In Authentication tab, enable AKS-managed Azure Active Directory, this will enable you to connect to cluster from your azure cli in your device (or in your CI runner) and control the cluster locally using kubectl commands.</li><li>In Networking tab: set network configuration to Azure CNI. This will create an Azure VPC instead of using default Kubernetes network, kubenet.</li><li>Create new container registry and enable admin user. You can use external private registry, like dockerhub or harbor.io. However, in this tutorial, I will use Azure Container Registry (ACR).</li></ul><p>Once cluster is created, open your local terminal and run the following commands:</p><pre>SUBSCRIPTION_ID=  # your subscription id when you created your acc.<br>RESOURCE_GROUP=  # The resource group you created.<br>CLUSTER_NAME=  # name of the kubernetes service.</pre><pre>az account set --subscription ${SUBSCRIPTION_ID}<br>az aks get-credentials --resource-group ${RESOURCE_GROUP} --name ${CLUSTER_NAME}</pre><p>Then, a command will prompt asking you to login by providing you a login URL and a code that you need to copy to a browser. Once authenticated, you can then apply any changes to the cluster from your command line. To test it, run the following command:</p><pre>kubectl get all --all-namespaces</pre><p>With that, you are actually getting all the information from your Azure cluster.</p><h3>Azure Container Registry</h3><p>If you went to your resource group in the portal, you would find two additional resources that have been created along with your cluster, namely Virtual Network and Container Registry. So now we need to build the production images and push them to ACR in order for the cluster to find them and pull them.</p><p>For starters, click on the container registry and navigate to <em>Access Keys</em>. There you can find the login server and the credentials that you need to login. In the cloned repository, modify .env file and set CR_URL to the value correspond to <em>login server</em>.</p><p>Then, docker-login to the registry by running the following command in your terminal:</p><pre>docker login -u ${ACR_USERNAME} -p ${ACR_Pass} <a href="https://${acr_url}/">https://${ACR_URL}</a></pre><p>Once successfully logged in, you can then build your production images and push them to the Container Registry using the following commands:</p><pre>docker-compose -f production.yml build<br>docker-compose -f production.yml push</pre><p>You can verify that they are pushed by navigating to <em>Repositories </em>tab in your Container Registry dashboard.</p><h3>Production Namespace</h3><p>Namespaces in Kubernetes is a way to logically isolate services or applications from each other. It is not always necessary to have but it offers several advantages and it is recommended per <a href="https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-organizing-with-namespaces">Kubernetes Best Practices</a>. Namespaces help:</p><ul><li>Enforcing roles and responsibilities between the teams, specifying who can access what in the cluster.</li><li>Partitioning landscapes, for example, logically separate staging and production services or app1 and app2.</li></ul><p>In almost every Kubernetes distribution, the cluster comes with several Virtual clusters. An important namespace namedKube-system, contains the Kubernetes system controllers and API. There are few cases where you need to modify the services inside it but it is not always necessary. Another namespace that Kubernetes distributors usually provide is a default namespace for you to create your services. It is called, well, default namespace.</p><p>As per best practices, it is better to organize your application using a namespace and assign the correct roles and responsibility for a team to access and modify it. For our use case, I will create a namespace called production. The following snippet shows how to create a namespace:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccf3359a1184cf668e20368ba5a02ed5/href">https://medium.com/media/ccf3359a1184cf668e20368ba5a02ed5/href</a></iframe><p>To deploy it, run the following command:</p><pre>kubectl apply -f compose/kubernetes/namespaces/production.yml</pre><h3>Next</h3><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-2-970f1d82b65f">In the next article</a>, I will cover setting up all the requirements prior to release and lunch the application. Moreover, I will cover configurations, secrets and shared volumes.</p><h3>Clean Up</h3><p>If you ran the tutorial, please go ahead and delete the resource group, Azure then will delete every resource in that group. Additionally, delete the service principal that has been created along with the resource group.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c5aa7e683ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/hands-on-day-1-and-day-2-operations-in-kubernetes-using-django-and-aks-part-1-2c5aa7e683ef">Hands-on Day 1 and Day 2 Operations in Kubernetes using Django and AKS — Part 1</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting and Forecasting Fatigue Damage of Automotive Components]]></title>
            <link>https://medium.com/compredict/predicting-and-forecasting-fatigue-damage-of-automotive-components-f6bf5f6bb9e2?source=rss-2c7c3c47e246------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6bf5f6bb9e2</guid>
            <category><![CDATA[predictive-maintenance]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[automotive-engineering]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Fri, 26 Jun 2020 13:45:25 GMT</pubDate>
            <atom:updated>2020-09-14T07:50:31.295Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This article is a continuation work on previous publication¹: Predicting and Forecasting the Lifetime of Automotive Vehicle Components.</blockquote><p>Nowadays, vehicle reliability is becoming an ever more important core aspect of automotive engineering to anticipate the trends towards car sharing and autonomous driving. The flawless operation of vehicles for a defined mileage under given loading and environmental conditions is crucial for cost and safety reasons. There are well-established methodologies in durability engineering to assess component reliability under certain constraints such as mileage or load, in order to retrieve a <strong>Remaining Useful Lifetime</strong> (RUL) estimation. These methods are based on damage accumulation, which are mostly semi-empirical approaches, consider only a limited number of variables and do not always capture real-life usage patterns and the actual environmental conditions a component is exposed to. Consequentially, automotive manufacturers and suppliers are forced to consider safety factors during dimensioning in order to minimize the impact of these uncertainties, which leads to over-design.</p><p>The objective of this research is to propose an approach to better estimate the fatigue damage by incorporating yet unconsidered factors and making use of fleet data. We trained a neural network model to leverage typical unconsidered factors such as temperature, road condition and individual usage patterns, and provide an improved RUL estimation for a vehicle component. Then, we use the output of the model to better forecast at which mileage the component will fail by training another neural network model.</p><p>Without further ado, I will illustrate how we generated the reality-like data to train the models of this study. Then, I will explain each model independently including their pre/post processing, model architecture and the final results. Eventually, I will demonstrate the flow on how we serve and online-train the models in production.</p><h3>Dataset</h3><p>Acquiring enough history of vehicles that failed for a specific component can take years to collect. Besides, fatigue damage is an unknown phenomenon, we can’t quantify the damage at any point in the vehicle’s history except when it fails.</p><p>So what we did is that we used real data generated from our Tesla Model3 and ran it in a simulation environment until a component failed, for the experiment, we monitored the rear side-shaft component of the vehicle. In the simulation environment, we control how this component is affected by the unconsidered factors, so we assumed that temperature, humidity and road condition have different and high nonlinear influences on the component lifetime based on the realtime behavior of the given factor. In order to not make the behavior deterministic, we also add some random noise amplifying or reducing the influence of the given factor at each time step. The following steps illustrate how we generate artificial vehicles in a nutshell:</p><ol><li>We collected the time series data generated from our Tesla Model 3 over 30,000 km.</li><li>We generated many trips with different mileage and time using the <a href="https://medium.com/compredict/generate-an-artificial-car-fleet-to-train-and-test-algorithms-a-concrete-use-case-of-drivereal-d7937bf5e9b3?source=collection_home---4------1-----------------------"><strong>driveREAL</strong></a><strong> </strong>algorithm.</li><li>We combined the trips together to build a car history.</li><li>For each trip, we compute two damages on the component: the damage computed based on the state-of-the-art formulas² (damage accumulation based on the Miner rule) that considers the load (torque) and the number of revolutions of the shaft for the given load. This damage value is denoted as <strong>Simple Damage </strong>and represents our baseline model. The other damage is the real damage that we configured in our simulation environment and that incorporates additional factors, nonlinearities and an undeterministic part. We denote it as <strong>Effective Damage.</strong></li></ol><p>The aforementioned process generated thousands of vehicles, where each vehicle has plenty of trips with the following feature space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*nV2kkEr6Zw786GrUROY4Vw.png" /></figure><p>After understanding the nature of the dataset and where it came from, let me re-phrase the objective of this research:</p><p><em>Given history of driving profiles generated by the driveREAL algorithm in the simulation environment using real driving profiles from our Tesla Model3, can we predict a damage information closer to the effective damage than the damage given by the state-of-the-art formula, i.e. the simple damage, by incorporating unconsidered but relevant factors along with the stress classes? This, noting that the effective damage can only be used for evaluation and never for training because it is unknown in reality. Then, can we use the improved estimation to forecast at what mileage this component will fail?</em></p><h3>Fatigue Prediction Model</h3><p>Due to the fact that in reality we usually only know the true damage value of a component when that component fails (i.e. the damage value is 1), this limits us to train the model solely on moment of failure which reduces the number of training instances drastically. This raises also another issue: we can’t train the model in supervised settings because the target will always be 1 given different histories of driving profiles.</p><p>To tackle the aforementioned problems, we build a model that learns the real damage using a proxy value, such as the ratio of the domain-expert damage value, i.e. the Simple Damage, to the damage at point of failure, i.e. at 1. We denote this ratio as <strong>Calibration Factor.</strong></p><p>After we identified the target, let’s discuss the feature space. The question resides in how can we incorporate the unconsidered factors with stress classes. We followed the method proposed by Bergmeir et al³ to aggregate the stress loads recorded at certain values. However the shortcomings of this preprocessing approach is that the number of features can grow huge by increasing the number of:</p><ul><li>Unconsidered factors.</li><li>Granularity / number of classes of each factor.</li></ul><p>Another problem is that it might generate a sparse matrix which could be harder to train. From a physical point of view, this means that we will have zeros in the matrix, since certain combinations of the factors are impossible. However, both problems can be solved by assuming in-dependency between the factors. Of course, this assumption can be costly as, in reality, the factors could be inter-dependent.</p><p>With data prepared, we trained a Deep MLP model on damaged vehicles to predict the Calibration Factor and predicted the damage at each trip for unseen testing vehicles. In order to assess the uncertainty of the model, we used Monte-Carlo Dropout layers to produce prediction intervals. Based on the results on unseen vehicles, the model is more confident on its predictions the more history a vehicle has. The following figure shows an example of two test vehicles. As a reminder, the Effective Damage of the test vehicles is only depicted for comparison reason. In the reality, this information is not available and accessible at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1Asa2uK1ltph6qX3oZEKA.png" /><figcaption>Dropout predictions for a MLP network, the solid green line is the mean of the prediction intervals with shaded area presenting one standard deviation.</figcaption></figure><h3>Fatigue Forecasting Model</h3><p>Once we have a better estimation of the damage, we can then forecast when a component will fail more accurately. So the first step for forecasting is to predict the fatigue damage for all trips of a given vehicle using our previous model. Since the damage predicted occurred in different dissimilar trips, i.e. trips with different distances which make the distance of the anticipated damage unknown, we had to make the distances between all trips constant using <strong>interpolation</strong> to compose damage values at certain distances within the range of the known given damage values.</p><p>Afterwards, we have <strong>de-seasonalized</strong> the damage because the lifespan damage is accumulative and has temporal dependencies, and Machine Learning models tend to perform better when we remove trend and seasonality components from time series.</p><p>Finally, a <strong>sliding window transformation</strong> is applied to extract features from a window of constant size. The features within the window will be split into <em>&lt;features, targets&gt;</em> subsets. The target space in the sliding window might not be enough to predict failure, especially if the interpolation value is small. For example, if the time interval between observations is one hour, then the forecasting horizon is also one hour, which is inconvenient in some cases. There are many different strategies to forecast multiple steps ahead⁴. However, none of these strategies is suitable for our case. Therefore, we developed a new strategy which combines the recursive multi-step forecast and multiple outputs approach in order to recursively predict a failure that will happen in the far future. In this hybrid approach, maximum number of multiple targets will be used in a sense that the dataset will still be big enough to train the model. Afterwards, we use the anticipated multiple outputs to forecast the next damage values recursively. The following figure shows the flow of the hybrid strategy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*YNgr4D0QVxStPcEqAV6Sfw.png" /><figcaption>Hybrid Multi Output and Recursive multi-step strategy to recursively forecast far future damages.</figcaption></figure><p>With that, the data is ready for training the forecast model, the model used is a Deep MLP that takes into account a history of 100 points that are interpolated at interval of 200km and outputs 50 points in the future, this allows us to predict 10,000km at one-shot, i.e., 200 * 50 = 10,000km.</p><p>The following figure shows the complete flow for training and forecasting damage model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*tFL_AU2-W73K0Fd8_DT9uw.png" /><figcaption>Steps for training and serving the forecasting model.</figcaption></figure><h3>End-to-End model</h3><p>At the end, we want to produce a system that can improve the estimation of the fatigue damage by incorporating unconsidered factors in its calculation and hence identify the lifetime of a component. Then, extend what has been learned to forecast the remaining mileage of a vehicle until failure. The artificial but realistic data we trained the models on are just to demonstrate that if the model worked in simulation environment, then it can perform in reality. However, in reality we don’t have enough broken vehicles in our fleet to train the model, so we first train the models to predict the damage computed by the state-of-the-art formula and with every <em>X</em> new trips or <em>N </em>broken vehicles we online train the models to improve the prediction.</p><p>Both models are trained in our ML Framework and hosted in AI Core, our Machine Learning-as-a-service platform. AI Core provides a capability to automatically join multiple models to create a hybrid model. Simply, it just creates a semantic pipeline that defines how and in which order the models it consists of, are run. The pipeline steps can run sequentially, in parallel or both (you can read further about ML Framework and AI Core in this <a href="https://medium.com/compredict/compredict-platform-architecture-part-1-ai-core-ml-framework-648bc2e1b841">article</a>). At the moment, each model is trained individually but the client can request the result of each model separately or jointly using the hybrid model.</p><p>Additionally, we run an offline job in a certain interval to check if there are new data in our fleet to online-train our models. For fatigue prediction model, we check if any vehicles have recently damaged the component we are monitoring, whereas for the forecasting model, we check if the vehicles in our fleet have X new trips.</p><p>The following figure shows the end-to-end flow for training and serving the models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*gTinYiXGDvsYWR_L3cTO3w.png" /><figcaption>Training, serving and improving the models and ensemble them to a hybrid model</figcaption></figure><h3>References</h3><p>[1] Ousama Esbel, Sebastian Kauschke and Stephan Rinderknecht, <strong>Predicting and Forecasting the Lifetime of Automotive Vehicle Components</strong>, in: 29. VDI-Fachtagung Technische Zuverlässigkeit 2019, Düsseldorf, pages 321–336, VDI Wissensforum GmbH, 2019</p><p>[2] Haibach, Erwin. <strong>Betriebsfestigkeit</strong>. Springer-Verlag Berlin Heidelberg, 2006.</p><p>[3] Philipp Bergmeir. <strong>Enhanced Machine Learning and Data Mining Methods for Analysing Large Hybrid Electric Vehicle Fleets based on Load Spectrum Data</strong>. Wissenschaftliche Reihe Fahrzeugtechnik Universität Stuttgart. Springer Vieweg, 2018.</p><p>[4] Souhaib Ben Taieb, Rob J Hyndman, et al. <strong>Recursive and direct multi-step forecasting: the best of both worlds</strong>. Working paper, 2012.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6bf5f6bb9e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/predicting-and-forecasting-fatigue-damage-of-automotive-components-f6bf5f6bb9e2">Predicting and Forecasting Fatigue Damage of Automotive Components</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMPREDICT Platform Architecture — Part 1: AI Core & ML Framework]]></title>
            <link>https://medium.com/compredict/compredict-platform-architecture-part-1-ai-core-ml-framework-648bc2e1b841?source=rss-2c7c3c47e246------2</link>
            <guid isPermaLink="false">https://medium.com/p/648bc2e1b841</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[platform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Wed, 05 Feb 2020 12:53:47 GMT</pubDate>
            <atom:updated>2020-09-14T07:54:05.093Z</atom:updated>
            <content:encoded><![CDATA[<h3>COMPREDICT Platform Architecture —Part 1: AI Core &amp; ML Framework</h3><p>We at COMPREDICT, provide many services to our partners in the Automotive Industry. These services range from in-car software, through managing data lake, to developing and serving AI models in the cloud. This series of posts will discuss the architecture and technology stack that allow us to accept streamed data, train models and serve them inside a car or in our cloud.</p><h3>Overview</h3><p>Our software-based approach, the <strong><em>COMPREDICT Platform</em></strong>, predicts component failure, personalizes maintenance plans, enables lightweight design and optimizes the development process for automotive components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvxwGD36akd6wOVDPkTPQg.png" /><figcaption>COMPREDICT Platform</figcaption></figure><p>The picture above describes our complete tech stack and the basic flow of our software, called <strong><em>COMPREDICT Platform</em></strong><em>.</em></p><p>In <a href="https://www.youtube.com/watch?v=Irqm-xIuFjw"><em>in-car software</em></a>, we provide embedded load and lifetime monitoring models to compute usage profiles and assess the lifetime of the components by using virtual sensors relying on sensor fusion and Neural Networks. In a nutshell, our embedded algorithms process and enhance the standard data available in every series-production car (e.g. CAN signals), in order to get access to durability-related information of the components. Once processed, we gather the data generated from the <em>in-car software</em> in an aggregated way by sending the data on a regular discrete schedule (preferred way for now), or in a real-time way by streaming time series. All steps of the <em>in-car software</em> are purely software-based, no additional hardware is required.</p><p>In <em>data lake</em>, we store all data we have (generated from our own vehicles, project-related data, data streamed or sent to us by our partners). Then, we apply ETL jobs on these data to transform them into useful information and use them for inference, training or simply store them in our data warehouse.</p><p>The intelligence unit in our platform is <em>AI Core</em> our algorithm hub, where we develop and serve all our models and expose them by a universal API. The <em>AI Core</em> administrates our algorithms and models, executes training processes when new data is available, and manages tasks, queue and priority.</p><p>Finally, to relieve the customer from the hustle of connecting to the <em>AI Core</em>, we provide an user interface that enables data visualization and stores the algorithms’ results on our web server along with several additional features tailored specifically for automotive engineers, fleet managers or drivers. We call it <em>COMPREDICT Analytics.</em></p><p>Each block will be discussed in depth in different blogs. For this post, I will introduce our Machine Learning Platform that we use to develop our models and how it interacts with our ML-as-a-Service platform, <em>AI Core</em>, where we will walk through in depth about its architecture and workflow.</p><h3>AI Core</h3><p>Our main assets are the state-of-the-art, patented and patent pending models that tackle different engineering domains in the automotive industry (software sensing, design optimization, monitoring and predictive maintenance, simulation tools, testing programs). These models are developed using various tools (Tensorflow, C++, Matlab, pyTorch, etc.). <em>AI Core</em> gathers all our developed algorithms in a single centralized hub and securely exposes these models to our internal team and external customers.</p><p>Additionally, <em>AI Core</em> is capable to run algorithms synchronously and asynchronously by dispatching long term jobs to a background queue system.</p><h4>Technology Stack</h4><p><em>AI Core</em> uses the following technologies:</p><ul><li><strong>Docker </strong>for local and production environment.</li><li>Python <strong>Django </strong>as web framework and <strong>Django Rest Framework</strong> as an API engine.</li><li><strong>Celery </strong>for asynchronous tasks that uses <strong>RabbitMQ </strong>as a queue system.</li><li><strong>Flower </strong>for queue monitoring.</li><li><strong>Postgres </strong>database.</li><li><strong>Dask </strong>to offer distributed training for heavy machine learning related algorithms.</li><li><strong>Python Boost</strong> and <strong>Matlab Runtime</strong> to run C++ and Matlab models respectively in python.</li></ul><h4><strong>Applications</strong></h4><p>Django hosts two applications:</p><ul><li><em>Algorithms: </em>Deals with serving and hosting Machine Learning &amp; Analytics Models.</li><li><em>Users</em>: Manages organizations, users, activities and permissions.</li></ul><p>Each application has its own API for connecting and requesting. For each API, we provide <a href="https://github.com/COMPREDICT-GmbH">SDKs</a> in different languages for fast integration.</p><p><em>Algorithms </em>application offers a base class abstract Model that provides convenient methods for serving models. These methods are overrode by sub-classes that are specialized for a specific model type. Moreover, there are five different types we support:</p><ul><li>C++ Model.</li><li>Fit/Unfit ML and NN models.</li><li>Matlab Model.</li><li>Hybrid Model (An ensemble of the above models).</li></ul><p>For each served model, you can specify the <em>evaluations </em>that you would like to apply to the the predicted values. This can be directly done in the API request by including the parameters of the evaluation method. For instance, most of our virtual sensor models for mechanical components are evaluated by using a <a href="https://en.wikipedia.org/wiki/Rainflow-counting_algorithm">Rainflow-counting method</a>, which is standardly implemented in our platform. Similarly, each served model is versioned, a client can request earlier versions as desired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*5X02uHFhUs7pN8lkv_jsAQ.gif" /><figcaption>API Quick response.</figcaption></figure><p>The API’s response solely depends on the type and the task of the model; it might require short amount of time to process. In this case, the response is sent directly to the client, as shown in the figure on the left.</p><p>On the other hand, the model may require plenty of time to process, hence, the request will be dispatched to the queue and a job id will be given to the requester to query the results later. Conversely, the requester can specify a callback endpoint where <em>AI Core</em> will send the results to once processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*uK7VJyVfb9NPcCqpLzvgtQ.gif" /><figcaption>API Request dispatched to the queue and response is queried later or POSTed to callback URL.</figcaption></figure><p>Each model has different inputs, outputs and evaluations. Upon listing the algorithms or getting a specific one, you can identify the following:</p><ul><li>The features that are mandatory for the algorithm and the expected output.</li><li>The file formats allowed (JSON, CSV, Parquet, tfrecords).</li><li>Whether it will be processed directly or dispatched to the queue.</li><li>List of the <em>evaluations </em>that the user can use to evaluate the predictions.</li></ul><h4>Privacy and Security</h4><p>At COMPREDICT, we value the privacy of the users. Therefore, <em>AI Core</em> doesn’t store any data sent by the user. However, when the request is escalated to the queue, the results will be locally stored for maximum of three days which gives the user the benefit to query the results at later point. This might cause an issue for certain users that have strict requirements to share the input/output to any 3rd party organization. In order to overcome this issue, we allow the users to configure the API to encrypt the results prior to storing them. The results can then only be decrypted by a key held by them. Likewise, we allow the users to send us encrypted input data, so that the data transit is secure in both directions.</p><p>The encryption mechanism used is the widely implemented RSA algorithm. RSA is a symmetric cryptographic algorithm that requires two different keys; a public key that anyone can hold and use to encrypt the data, and a private key to decrypt the data and should always be kept private. In addition, we use PKCS1 OAEP padding scheme which semantically secure under <em>chosen plaintext attack.</em></p><p>However, once received, we need to decrypt the data in order to run training or inference tasks. After the task is done, the data are then re-encrypted before transfer. To overcome this decryption and re-encryption steps, we are conducting many researches, in collaboration with TU Darmstadt, in the area of developing end-to-end private machine learning models, like using Partial Homomorphic Encryption for training and inference. However, this comes at a cost of jeopardizing the performance of the model.</p><p>In another note, the requests are authenticated using Bearer Authentication. Furthermore, not all algorithms are exposed to the users, each user is configured to access limited list of algorithms. In addition, we use throttling to control the number of requests per user. Based on their subscription option, we can increase the amount of requests they can send per minute and per day.</p><h4><strong>Deployment</strong></h4><p><strong><em>COMPREDICT Platform</em></strong> in general, and specifically <em>AI Core,</em> follow the design principles of microservices architecture. These services are managed and orchestrated by Kubernetes. The reason behind this choice is that it allows us to distribute the application load and ensure stability with replicable and scalable services interacting with each other. For instance, this helps us to separate the loads between different <em>organizations </em>by creating different queues for each one. Hence, for each newly created <em>organization </em>in the dashboard (Managed by <em>Users</em> app), Django will trigger RabbitMQ to create a new queue, and workers are spawned to specifically serve this queue. This helps us to track how much resources each <em>organization </em>consumes. Consequently, we can then adapt the subscription service, if the customer requires more loads and and wants us to scale up the workers of this queue.</p><p>Each queue is prioritized. Moreover, a request can be processed according to a given priority, based on the requester and the requested algorithm. Being that, a user with more permissions can have his/her requests processed faster than a normal user in the same instance.</p><p>Depending on the requested training or inference tasks, our customers may send us huge files for processing (i.e. GBytes of data). Moving these files back and forth between the services is costly. This is mitigated by sharing a scalable, on demand space between the containers. Furthermore, once the data is uploaded, the file will be temporarily stored in the shared space until a worker finish processing it.</p><p>Currently, <em>AI Core</em> is deployed in AWS using the following services EKS, RDS and EFS. However, we recently became partners with Open Telekom Cloud and Microsoft Azure, and we are assessing their capabilities to finally choose which one is best for hosting the solution or parts of it.</p><h3>Machine Learning Platform</h3><p>The motivation behind building a standard tool for building and developing ML and NN models is that there was no reliable, uniform and reproducible pipelines among the data science team.</p><p>Additionally, as we have been working in the last years with different OEMs for various tasks, we were able to identify the best models and architectures that work for specific cases in Automotive Industry. Therefore, we have centralized and built different libraries to:</p><ul><li>Optimize the best models for the task and ease the ability to do transfer learning for similar tasks,</li><li>Analyze and process signals and time series.</li><li>Analyze fatigue of materials.</li></ul><p>This platform is connected to our <em>Feature Store</em> to help our team query the necessary data for the specified task.</p><h4>Technology Stack</h4><p>The platform is a combination of containerized open-sourced frameworks that are further extended to meet our needs:</p><ul><li><a href="https://mlflow.org/"><strong>MLFlow </strong></a>for tracking experiments and storing model’s artefacts.</li><li><strong>Postgres </strong>to store the results of the experiments’ details.</li><li><a href="https://github.com/ml-tooling/ml-workspace"><strong>ML-workspace</strong></a> for managing and standardizing the libraries and tools that a data scientist would need.</li><li><a href="https://github.com/ml-tooling/ml-hub"><strong>ML-hub</strong></a> for spawning and managing the data science team environment.</li></ul><p>ML-workspace is extended to spawn our specified image that includes our built-in libraries.</p><h4>Application</h4><p>Beside managing the environment and libraries, we standardized the project structure. For instance, we extended ML-workspace so that, whenever a new project is created, a certain project skeleton is built and pulled from our Git in order to quickly kick-start the core tasks.</p><p>A project is solely controlled by a JSON configuration file, where the data scientist can set the path to the features and targets, and tweak the feature selection, preprocessing, model parameters, cross-validation, etc... Besides, the user has full control of the project and can further modify it to meet the specific project’s needs.</p><p>Once the model is trained, evaluated and compared with other experimented models, the model along with its preprocessing statistics can be pushed to <em>AI Core</em> through the <em>Algorithms </em>API and is then ready for serving customers. Alternatively, it can be exported and deployed somewhere else, like in a vehicle ECU.</p><h4>Deployment</h4><p>The main server is currently deployed on-premises equipped with various high-performance GPUs from Nvidia. As well, and especially for cross-research, we use AWS EC2 equipped with GPUs or AWS Sagemaker.</p><h3>Conclusion</h3><p>In this post, I have briefly talked about the overview of the <strong><em>COMPREDICT Platform</em></strong>. Then, I explained in details two aspects: <em>AI Core </em>and <em>ML Framework</em>. The following figure shows the current version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UU0ZRffAm7DTkFHbQyIr9g.png" /><figcaption>COMPREDICT Platform: Unpack AI Core and <em>ML Framework</em></figcaption></figure><p>In the next post, we will discuss the<em> in-car software</em> along with our <em>COMPREDICT Analytics </em>platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=648bc2e1b841" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/compredict-platform-architecture-part-1-ai-core-ml-framework-648bc2e1b841">COMPREDICT Platform Architecture — Part 1: AI Core &amp; ML Framework</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Causality for Machine Learning Interpretability]]></title>
            <link>https://medium.com/compredict/time-series-causality-for-machine-learning-interpretability-97fdb9fd979?source=rss-2c7c3c47e246------2</link>
            <guid isPermaLink="false">https://medium.com/p/97fdb9fd979</guid>
            <category><![CDATA[causality]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[feature-selection]]></category>
            <category><![CDATA[virtual-sensor]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Ousama Esbel]]></dc:creator>
            <pubDate>Thu, 26 Sep 2019 11:36:09 GMT</pubDate>
            <atom:updated>2020-09-14T07:56:25.577Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="https://compredict.de/">COMPREDICT GmbH</a>, we work mostly with highly redundant multivariate time series generated by automotive industry to reconstruct a sensor, forecast a specific event or classify a behavior using Machine Learning and Neural Networks. In Automotive industry, a vehicle can generate more than 40,000 signals and megabytes of data in matter of milliseconds. Being that, in order to narrow down the important features that cause the target, we need to understand the given data and select them for training our models. Therefore, we study the features that correlate/cause the target to help us build less complicated models and prevent <strong>multicollinearity</strong> issue in machine learning. Unfortunately, state-of-the-art feature selection techniques fail to exploit the importance of features in such time series because they lose the temporal information among the features at different intervals (i.e. phase shift between the features). For this issue, we depend on Causal Inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKnMCKh09_AJYfEU-x5tBQ.png" /><figcaption>Correlation vs Causation. Image taken from <a href="https://amplitude.com/blog/2017/01/19/causation-correlation">here</a>.</figcaption></figure><h3>Causal Inference</h3><p>Causal Inference or Causality (also “causation”) is the relation connecting cause and effect. Both cause and effect can be a state, an event or similar. In time series analysis the term “causality” is used to relate variables based on how much possible influence or effect one variable has on another. In this blog, several data-based measures that are said to measure causal relations between time series variables are shortly presented and evaluated against data generated by automotive vehicle. These measures can be seen as functions operating on the values of two time series:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*MTfjjnk95-ht6bHrwmDJag.png" /></figure><p>The measures quantify the degree in which one variable causes, influences or affects another. This relationship is assigned a single value of intensity, where a higher causal value means the observed effect is greater. For simplicity, the causality is computed as a one-to-one relation (bivariate) capturing different possible cause-and-effect relationships (linear, non-linear, etc.). Some measures that quantify the causation are:</p><ul><li>Granger Causality (GC): a statistical concept that linearly quantifies causation by measuring how much the past of variable <em>X</em> helps predicting variable <em>Y.</em></li><li>Transfer Entropy (TE): an information-theoretic concept with relations to both mutual information and Granger Causality.</li><li>Cross Convergent Mapping (CCM): based on Taken’s Theorem. It proves that, for dynamical systems with variables considered as various dimensions, the principle dynamics of the system can be reconstructed by an embedding of lagged versions of one single variable.</li></ul><p><em>Each of the mentioned measures will be explained more in depth in different future posts.</em></p><p>The above mentioned causality measures have their own pros and cons but they can quantify the degree of causation of the features towards a target. Furthermore, they can help us choose the best <em>N</em> features that can predict a target and build a model trained on these features. However, there is a high possibility that a subset of the chosen <em>N</em> features can be highly correlated with each other, particularly in a feature space that contains many redundancies. This will affect the interpretability of the model and, in some cases, it would affect the performance of the model. For example, in the automotive industry, there can be two signals that are giving access to the same physical value but one applies a filter or a smoothing function. Both variables might have been chosen as variables that highly cause the target by a causation measure. However, while building a prediction model, one variable is enough for building the model as the second variable is redundant.</p><h4>Choosing Best Features</h4><p>A naive approach to variable selection using bivariate causal measure is to consider all possible inputs in isolation. Sorting the input variables based on their causal contribution towards a target variable gives a simple ranking of relevance of each input.</p><p>Another approach to select the best uncorrelated features and solve the multicollinearity issue, is to compute the causation matrix among all variables in the dataset and cluster the features by converting the causation matrix to distance or affinity matrix to build the clusters. Then, for each cluster, one can chose the highest causal value that contributes towards the target.</p><p>In addition to clustering, we can use statistical approach and convert the causation matrix to a directed graph with probabilities associated with each outgoing edge of a node. Then, we can apply a stochastic or deterministic process to determine the best route from target to the features, such as Random Walk.</p><p>To recapitulate, the process to narrow down the number of features to the best features that cause the target requires two steps:</p><ol><li>Compute the causation matrix between the features or a pair-wise causation towards the target using one of the described causality measures.</li><li>Select a number of features based on the causation results.</li></ol><h3>Study Case</h3><p>The dataset consists of signals captured by a Controller Area Network (CAN) bus, which is the main communication node for most passenger vehicles. Various driving maneuvers were performed during the measurement process. The number of time series features is 122, including the target. The task is to predict the torque acting on a rotating component in the vehicle drivetrain.</p><p>As for evaluation, the mentioned approaches to variable selection are evaluated by comparing the predictors of models trained on the respective selected variables.</p><p>Beside the causation measurements, we use Pearson correlation as a baseline to measure the performance of the different approaches. Pearson correlation is a symmetrical measure of linear correlation between two variables. It is computed as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*FfYMYl2PaBzr227k_jNRzQ.png" /><figcaption>Pearson Correlation Equation</figcaption></figure><p>The following figure shows the stages of the prediction pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lv0qkM_1xo3cSNc9XIEVVQ.png" /><figcaption>Prediction Pipeline.</figcaption></figure><p>The results are displayed as following: The test loss is plotted over varying input sizes for a fixed measure (e.g. “Granger Causality”) or a fixed method (e.g. “Effect-on-target”). The test loss of a model trained on all variables is always included and marked by a dashed line. Some data points were removed in the graphs below due to the fact that the corresponding methods fail at reaching satisfactory results. The mentioned data points were removed to keep the plots clear and consistent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*AMEFnNug6jz8GjrA3wfjQg.png" /><figcaption>Results for the prediction using different selection methods.</figcaption></figure><p>Regarding the measures of causality that were tested, all seem to be usable as possible metrics for variable selection for prediction tasks. The causal values extracted using Correlation, Granger causality, Transfer Entropy and Convergent Cross-Mapping seem to capture at least some kind of relationship between variables that is relevant for a possible prediction model. Interestingly, for the presented problems, the measures capturing only linear relationships (Granger causality and correlation) are not less successful in finding reasonable variable sets than the non-linear approaches (Transfer Entropy and Convergent Cross-Mapping).</p><p>Nevertheless, we have made many simplification assumptions on our approach, such as, linearity, number of considered past observations, bivariate causation or correlation which can further improve the selection of related features.</p><h3>What’s next?</h3><p>We are currently testing the robustness of these measures and methods with respect to other cases and benchmark datasets. Additionally, we are trying to address the assumptions we made on the mentioned causal measurements For instance, the causal measurements are measuring causality in one-to-one relations. However, a variable can cause another in combination of a third variable. This is called <strong>Multivariate Causal Inference.</strong> Despite the fact that corresponding approaches provide higher precision, the computation grows drastically if the feature space is big.</p><p>Finally, we are currently looking into more advanced causal discovery using <strong>Neural Granger Causality</strong> and <strong>Attention-based Neural Networks</strong> as the statistical methods do not exploit the representational power of deep learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97fdb9fd979" width="1" height="1" alt=""><hr><p><a href="https://medium.com/compredict/time-series-causality-for-machine-learning-interpretability-97fdb9fd979">Time Series Causality for Machine Learning Interpretability</a> was originally published in <a href="https://medium.com/compredict">COMPREDICT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>