<?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 Anshuman Tripathi on Medium]]></title>
        <description><![CDATA[Stories by Anshuman Tripathi on Medium]]></description>
        <link>https://medium.com/@anshumantripathi?source=rss-27b7e6a4a92d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-EgWQHj-c0unazrRYkGwuQ.png</url>
            <title>Stories by Anshuman Tripathi on Medium</title>
            <link>https://medium.com/@anshumantripathi?source=rss-27b7e6a4a92d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:39:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anshumantripathi/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[Self-Hosting on NAS: Docker Compose, Ansible and Tailscale Setup]]></title>
            <link>https://medium.com/@anshumantripathi/self-hosting-on-nas-docker-compose-ansible-and-tailscale-setup-37962b6a69b1?source=rss-27b7e6a4a92d------2</link>
            <guid isPermaLink="false">https://medium.com/p/37962b6a69b1</guid>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[tailscale]]></category>
            <category><![CDATA[restic]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Anshuman Tripathi]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 05:17:05 GMT</pubDate>
            <atom:updated>2026-08-20T05:14:46.621Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I use Docker Compose, Ansible, and Tailscale to run self-hosted apps on a UGREEN NAS, including backup with Restic and Backblaze B2</h4><p>In this post I cover how I set up my homelab with Docker Compose, Tailscale, and Ansible on my UGREEN NAS for self-hosting.</p><p>Before I delve into how my platform is setup, let me explain my usecases.</p><h3>How I use my NAS</h3><h4>Storage</h4><ul><li>I want to consolidate my storage into my NAS. All my digital documents, images, media should be backed up on NAS.</li><li>Although this would considerably reduce my usage of Google Drive and iCloud, my NAS would not be a full replacement for either. For sensitive documentation, I will keep a copy in Google Drive and have it synced to my NAS. This improves redundancy for highly important documents and data.</li></ul><h4>Self-Hosting</h4><ul><li>Accessibility of data in a secure manner is critical. Since this hosts all my and my family’s documents this should not be exposed to the internet.</li><li>Since my NAS supports running docker containers, I can host some applications on it.</li><li>These apps would need to be secure as well and should not be exposed to the internet <em>as much as possible</em>.</li></ul><h3>Platform Setup</h3><p>Let’s see how to setup a platform layer to support the above mentioned usecases.<br>Since UGREEN NAS comes with Debian installed, we can use apt for package management.</p><h4>Networking and secure access</h4><p>As I mentioned in the <a href="https://anshumantripathi.com/blog/self-hosting-hardware-infrastructure">previous post</a> that I am using <a href="https://tailscale.com/">Tailscale</a> for networking and secure access solution.</p><h3>Setting up Tailscale</h3><p>Setting up Tailscale is very straightforward.</p><ol><li>Create an account on Tailscale.</li><li>On the NAS, install tailscale with apt install tailscale.</li><li>Run tailscale login and login to Tailscale.</li><li>Approve the machine from the Tailscale admin dashboard.</li></ol><p>Once the machine is approved from the admin console, it joins the “tailnet” i.e., the tailscale VPN network. Tailscale assigns an IP and a domain using its MagicDNS system. This machine can then be accessed from anywhere through the tailnet by using the domain name.</p><h4>The DNS fight</h4><p>Setting up Tailscale on the NAS surfaced a recurring problem: UGOS manages /etc/resolv.conf itself and periodically rewrites it with its own nameservers. Tailscale&#39;s MagicDNS normally inserts 100.100.100.100 into /etc/resolv.conf so that tailnet hostnames resolve, but on UGOS, that entry keeps getting clobbered. This is the inverse of the problem Tailscale describes in their docs.</p><p>When that happens, tailscaled falls back to sniffing whatever is in /etc/resolv.conf for its upstream resolvers. When UGOS writes nameserver 127.0.0.1 (its local resolver), tailscaled picks that up, but tailscaled runs in its own network stack and cannot actually reach the host&#39;s loopback. Those DNS queries time out, tailscaled returns SERVFAIL, and public name resolution breaks. apt update failing on the NAS is usually the first symptom.</p><p>Bouncing tailscaled “fixed” it temporarily because the re-sniff sometimes landed on a cleaner resolver list. Pure entropy. The bug always came back.</p><p><strong>The fix:</strong> configure explicit Global nameservers (Cloudflare and Google) in the Tailscale admin console under <em>DNS → Nameservers</em>, with <em>Override DNS</em> enabled. This makes tailscaled use those resolvers exclusively and stop sniffing /etc/resolv.conf entirely. The 127.0.0.1 loopback failure mode is gone.</p><h3>Running containers? Then you must be using Kubernetes!</h3><p>I work with Kubernetes in my day job all the time and I also contribute to Kubernetes so using Kubernetes when working with containers would be my first instinct. But then on actually evaluating my problem statement, I realized that the tradeoff of using Kubernetes does not work well in this situation.</p><ul><li>In a self hosted setup, Kubernetes also brings in the complexity of managing the control plane and nodes.</li><li>I only have 1 physical machine, my NAS. To run a full Kubernetes cluster I would have to spin up VMs for control plane and nodes and then deploy my services over it.</li><li>I can use K3S but that’s additional overhead for minimal gains.</li><li>Kubernetes upgrades become a whole activity that would take me too much time and any mistakes could cause serious issues with the whole setup.</li></ul><p>The benefits of using Kubernetes are flexible scaling, providing high availability, self-healing, and orchestration of containers across multiple nodes. None of these apply to my usecase.<br>I am okay with running singular instances of my applications and their dependencies on my singular node (NAS). My uptime requirements are not strict. If a service is down I can take my time and fix it in a day or two.<br>The tradeoffs that come with Kubernetes are significant.</p><p>Although using Kubernetes here would be a good exercise to enhance my operational chops, this is not something I wanted to do on a day-to-day basis especially when I had services attached to this setup.<br>A simple docker-compose approach keeps my maintenance overhead low. I can automate docker-compose setup with Ansible by creating templates.</p><h3>Ansible? not Terraform?</h3><p>I wanted to manage my NAS configurations as code and Terraform again would be my instinctual first thought. And yet again on further evaluation this was clearly not the right choice. Yes I want to use Infrastructure as Code and although Terraform has become the de facto IaC tool, its tradeoffs outweigh the gains here.<br>Terraform does an excellent job maintaining Cloud Infrastructure at scale but because it provides that scale and manages a fleet of infrastructure resources, state management is a small price to pay. That tradeoff does not hold for my usecase.<br>In my case, my “infrastructure” is self hosted with 1 node which is literally my NAS. State management at this scale is a real issue. I can’t keep my state on my NAS to ensure its integrity in case of NAS failures. Putting it elsewhere requires opening up networking and paying for a storage service like S3 or GCS.</p><h3>How about Puppet or Chef?</h3><p>Puppet and Chef are good configuration management tools and could provide the automation I need here but both of these tools work on an agent model. They work by deploying worker agents on the remote machines which are managed by a server. This again felt like over-engineering for a single node.</p><p><strong>This led me towards Ansible which was perfectly tailored to solve this problem for me.</strong></p><h3>Ansible setup</h3><h4>Repository Structure</h4><p>I keep my NAS configuration in a GitOps repository structured like this:</p><pre>planetexprsnas/<br>├── ansible/<br>│   ├── site.yml               # Deploy all stacks<br>│   ├── deploy-stack.yml       # Deploy a single stack by name<br>│   ├── bootstrap-nas.yml      # Automate fresh NAS setup<br>│   ├── inventory.ini          # Local and remote SSH targets<br>│   ├── group_vars/all.yml     # All stack definitions (single source of truth)<br>│   └── roles/<br>│       ├── stack-deploy/      # Generic Docker Compose deployer<br>│       └── backup/            # Restic + database dump setup<br>├── stacks/<br>│   ├── _shared/<br>│   │   └── tailscale-sidecar.yaml<br>│   └── &lt;service&gt;/<br>│       └── stack.yaml<br>└── tailscale-configs/<br>    └── &lt;service&gt;.json</pre><p>The key design principle: group_vars/all.yml is the single source of truth for every stack: its env vars, paths, and secret references. Ansible reads this at deploy time, resolves secrets from gopass, renders a stack.env file, and runs docker compose up. Adding a new service means adding one entry there and dropping a stack.yaml in stacks/.</p><h4>Ansible Installation</h4><ul><li>Install pipx using apt-get install pipx. pipx installs and runs end-user Python applications in isolated environments. It fills the same role as macOS’s brew, JavaScript’s npx, and Linux’s apt. Under the hood it uses pip, but unlike pip it creates a separate virtual environment for each application, so their dependencies never collide and an uninstall leaves nothing behind. <a href="https://anshumantripathi.com/blog/self-hosting-platform-setup/#fn:2">2</a></li><li>Install ansible with pipx install ansible.</li></ul><h3>Docker Setup</h3><p>Although UGREEN NAS comes with a pre-installed Docker app, which can be used to create and manage containers, I find <a href="https://www.portainer.io/">Portainer</a> provided me with a better experience for container setup.<br>I will talk more about how it gets installed in the upcoming posts about installing apps.</p><h3>Backup Strategy</h3><p>3–2–1 is a good rule of thumb for data protection. In my case I have 3 copies of media (1 in actual copy, 1 in a RAID5 replica, 1 in Backblaze backup), on 2 locations (NAS and Backblaze) with 1 cloud storage (Backblaze).<br>It can be debated that RAID5 replica is not a true copy, I consider it as a copy here because I can use different drives to rebuild my existing drive.</p><p>As mentioned in the previous post, I use restic for my backup automation. The backup setup is managed by Ansible.</p><h4>Restic with Backblaze B2</h4><p><a href="https://restic.net/">Restic</a> is an open-source backup tool. It deduplicates, compresses, and encrypts data before sending it offsite. I back up to <a href="https://www.backblaze.com/cloud-storage">Backblaze B2</a> using its S3-compatible API, which restic supports natively.</p><ul><li><strong>2:00 AM daily:</strong> Databases are dumped to a local staging directory first. Databases need a consistent snapshot, so a live file copy would be unsafe.</li><li><strong>2:30 AM daily:</strong> Restic picks up the staging directory along with application data, photos, media, and configs, and pushes everything to B2.</li><li><strong>4:00 AM Sunday:</strong> Restic prunes old snapshots based on the retention policy.</li></ul><p>The backup runs on two schedules via systemd timers:</p><p>The retention policy keeps the last 7 daily snapshots, 4 weekly, and 6 monthly. This gives a recovery window of roughly 6 months with granular recent history.</p><p><strong>What is not backed up:</strong> container images, caches, transcode directories, and ephemeral log data. These are either regeneratable or not worth the storage cost.</p><p>Backup health is monitored via Prometheus metrics written after each run. A Grafana alert fires if a backup has not completed in the last 25 hours.</p><h3>What’s Next</h3><p>At this point the platform layer is in place. Tailscale handles secure access to the NAS over a private network. Docker Compose manages the container runtime, with Ansible automating deployments from a single GitOps repository. Restic keeps daily backups flowing to Backblaze B2.</p><p>This sets the foundation for actually running applications. In the next post I will walk through how I install and configure apps on this platform, how each service gets its own Tailscale identity, and how the sidecar pattern ties it all together.</p><h3>References</h3><ul><li><a href="https://tailscale.com/docs/reference/faq/dns-resolv-conf">https://tailscale.com/docs/reference/faq/dns-resolv-conf</a> <a href="https://anshumantripathi.com/blog/self-hosting-platform-setup/#fnref:1">↩︎</a></li><li><a href="https://pipx.pypa.io/stable/">https://pipx.pypa.io/stable/</a> <a href="https://anshumantripathi.com/blog/self-hosting-platform-setup/#fnref:2">↩︎</a></li><li><a href="https://restic.readthedocs.io/en/stable/030_preparing_a_new_repo.html#backblaze-b2">https://restic.readthedocs.io/en/stable/030_preparing_a_new_repo.html#backblaze-b2</a> <a href="https://anshumantripathi.com/blog/self-hosting-platform-setup/#fnref:3">↩︎</a></li></ul><p><em>Originally published at </em><a href="https://anshumantripathi.com/blog/self-hosting-platform-setup"><em>https://anshumantripathi.com</em></a><em> on August 18, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37962b6a69b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Hosting on a NAS: Hardware and Infrastructure Setup]]></title>
            <link>https://medium.com/@anshumantripathi/self-hosting-on-a-nas-hardware-and-infrastructure-setup-207d86f12f46?source=rss-27b7e6a4a92d------2</link>
            <guid isPermaLink="false">https://medium.com/p/207d86f12f46</guid>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[tailscale]]></category>
            <category><![CDATA[self-hosting]]></category>
            <dc:creator><![CDATA[Anshuman Tripathi]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 20:18:22 GMT</pubDate>
            <atom:updated>2026-08-19T22:12:47.970Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Setting up my self hosting infrastructure</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UKGvNRhHnwEUMiJw.png" /></figure><h3>Problems</h3><p>Recently I have been running into a few problems:</p><ul><li>Paying for multiple subscriptions (iCloud &amp; Google Drive) for general storage.</li><li>A change in TOS of any service can lead to losing access to personal data without a heads up.</li><li>Most of the storage was used by photos. I needed a photos platform that is shareable and accessible and separate from Google while providing good indexing and storage capabilities.</li><li>Usage of public tools and services. For example github-readme-stats’s public instance is used so much that it is generally down because of GitHub’s rate limiting.<br>– GitHub has been running into a lot of issues. I use GitHub to make sure my code is safely stored and available regardless of what machine I’m on, or if my computer/laptop crashes.</li></ul><h3>Solution</h3><p>I need a solution which I can control for storage and share with my family and friends as needed without relying on a third party.</p><ul><li>Although I needed something storage heavy, I also needed capability to run my own applications.</li><li>NAS looks like an ideal choice here.</li><li>With a NAS I can host open source applications like <a href="https://immich.app/">Immich</a>, <a href="https://forgejo.org/">Forgejo</a> and <a href="https://github.com/anuraghazra/github-readme-stats">github-readme-stats</a>.</li></ul><h3>My self-hosting infrastructure on my NAS</h3><ul><li>I use a <a href="https://ai.ugreen.com/products/ugreen-nasync-dxp4800-plus-nas-storage">UGREEN DXP-4800 Plus 4-bay NAS</a>.</li><li>Added two 1 TB SSD cache drives to it for faster data read/writes when accessing.</li><li>Upgraded RAM to 64 GB</li><li>Using RAID5 with 4 6TB HDDs (5.4TB usable each) giving me ~16TB of usable storage. This can be upgraded later as needed.</li><li>Attached the NAS to 10 gbps ethernet to ensure transfers were fast over the local network.</li><li>Set up Tailscale for secure access without exposing my NAS to the internet.</li></ul><h3>Setup</h3><h4>Using tailscale for secure access</h4><p>Although UGREEN provides a built in UGREENlink to connect remotely to the UGREEN NAS through the internet it does mean the NAS is exposed to the internet.<br>I did not want my NAS to be accessible over the internet. To keep my access secure I went with <a href="https://tailscale.com/">Tailscale</a>.<br>It provides secure connectivity for 100 devices and 5 users for free and it is easy to setup. Furthermore, each connected device gets their own domain through Tailscale’s MagicDNS making discovery and connectivity very smooth.</p><p>Although RAID5 provides some reliability for data, it’s not a true backup. To ensure data safety and recoverability I am using <a href="https://www.backblaze.com/cloud-storage">Backblaze B2</a>, which is S3-backed storage. It stores the snapshot backups of my NAS.<br>Backblaze B2 is a very affordable service. I am using <a href="https://restic.net/">restic</a> to manage my backups. More details on how restic is set up will be in an upcoming post.</p><h3>What’s Next</h3><p>This covers the hardware and network foundation of my setup: the NAS, storage, secure remote access, and backups. In the next post, I’ll go over the platform layer running on top of this — the apps I’m self-hosting and how I use Ansible to keep the whole thing reproducible.</p><p><em>Originally published at </em><a href="https://anshumantripathi.com/blog/self-hosting-hardware-infrastructure/"><em>https://anshumantripathi.com</em></a><em> on August 15, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=207d86f12f46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pods can go invisible in Kubernetes. Let’s find them]]></title>
            <link>https://medium.com/@anshumantripathi/pods-can-go-invisible-in-kubernetes-lets-find-them-c41d46986979?source=rss-27b7e6a4a92d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c41d46986979</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kubernetes-security]]></category>
            <category><![CDATA[kubelet]]></category>
            <category><![CDATA[kubectl]]></category>
            <dc:creator><![CDATA[Anshuman Tripathi]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 03:14:40 GMT</pubDate>
            <atom:updated>2025-10-27T03:41:58.305Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Kubernetes pods can become invisible to kubectl, creating security risks. A hands-on tutorial explaining how this can happen and its consequences</em></p><p>In Kubernetes, pods can become completely invisible to kubectl get pods -A while still running containers on the nodes. This behavior allows attackers to use it for persistence on exploited Kubernetes clusters.</p><p>I discovered this scenario through <a href="https://labs.iximiuz.com/challenges/kubernetes-invisible-pod-0bf2109b">an exercise on Ivan Velichko’s platform</a> by <a href="https://sagikazarmark.com/">Mark Sagi-Kazar</a> which is based on <a href="https://www.youtube.com/watch?v=GtrkIuq5T3M">a talk by Rory McCune</a> about Kubernetes security. Both are excellent resources for learning about concepts that are not widely known. Ivan’s platform <a href="https://iximiuz.com/en/">https://iximiuz.com/en/</a> provides great hands-on labs covering fundamentals of Containers, Networking, Linux, Kubernetes and more.</p><blockquote><em>Before moving forward I would recommend attempting the exercise and trying to find the solution.</em></blockquote><h3>Concepts</h3><p>Before we dig into solving the exercise let’s touch on some important concepts in Kubernetes. At this point I assume the reader has a working understanding of Kubernetes. If needed I would recommend going through my previous post about <a href="https://anshumantripathi.com/blog/understanding-kubernetes">Kubernetes Concepts</a>.</p><h3>Kubelet</h3><p>The Kubelet in Kubernetes runs outside the jurisdiction of the Kubernetes cluster. It runs as a systemd service on a Kubernetes node. This is because an external service is needed to manage and orchestrate containers which themselves are not containers.</p><p>This allows the Kubelet to bootstrap key control plane components on control plane nodes like the api-server, etcd, scheduler and controller-manager as <a href="https://anshumantripathi.com/blog/invisible-pods/#static-pods">static pods</a>. Once these critical components are up and running <em>the kubelet registers the static pods as </em><a href="https://anshumantripathi.com/blog/invisible-pods/#mirror-pods"><em>mirror pods</em></a><em> on the api-server</em>.</p><h3>Static Pods</h3><p>Static pods are pods managed by the kubelet which are created from manifests added in path /etc/kubernetes/manifests/ on the node. Any Pod manifest added here will be used by the kubelet to create a mirror pod.</p><h3>Mirror Pods</h3><p>Mirror pods are entries of a static pod in the api-server. These are only references to the actual static pods.<br>This means doing kubectl operations like edit, delete, etc. would not affect the pod because the Kubelet treats the manifest present on the node as the source of truth.<br>The kubectl commands on the other hand send requests to the api-server and try to update the mirror pod. After the saved update, the kubelet detects changes, applies the changes from its manifest and sends the updated information to the api-server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*_MIKxnP0TpaYhCcShuZ4zw.png" /><figcaption>Static pods and Mirror pods in Kuberentes</figcaption></figure><h3>Invisible Pods</h3><p>Now that we understand about static pods and mirror pods, let’s see how we can make a pod invisible. You can find all following examples in this git repo — <a href="https://github.com/AnshumanTripathi/invisible-pods">https://github.com/AnshumanTripathi/invisible-pods</a>.</p><p>Let’s create a <a href="https://kind.sigs.k8s.io/">KinD</a> cluster for our exercise</p><pre>kind: Cluster<br>name: test-cluster<br>apiVersion: kind.x-k8s.io/v1alpha4<br>nodes:<br>  - role: control-plane<br>  - role: worker<br>    extraMounts:<br>      - hostPath: ./static-pod.yaml<br>        containerPath: /etc/kubernetes/manifests/static-pod.yaml<br>        readOnly: false<br>  - role: worker</pre><p>This sets up a Kubernetes cluster with a control plane node and a worker node running a static pod. Here is the manifest of the static pod</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: podinfo<br>  labels:<br>    app: podinfo<br>spec:<br>  containers:<br>  - name: podinfo<br>    image: stefanprodan/podinfo:latest<br>    ports:<br>    - containerPort: 9898<br>      protocol: TCP<br>    resources:<br>      requests:<br>        memory: &quot;64Mi&quot;<br>        cpu: &quot;100m&quot;<br>      limits:<br>        memory: &quot;128Mi&quot;<br>        cpu: &quot;200m&quot;</pre><p>This sets up a pod in the <em>default</em> namespace running a <a href="https://github.com/stefanprodan/podinfo">podinfo container</a>.<br>We can see the pod is a static pod since it is managed by the Node (Kubelet).</p><pre>❯ kubectl get pod podinfo-test-cluster-worker -o jsonpath=&quot;{.metadata.ownerReferences[0].kind}&quot;<br>Node%</pre><p>Now let’s change the namespace of the static pod. To update the static pod, either change the static-pod.yaml, delete the kind cluster with kind delete cluster --name test-cluster and recreate the cluster.<br>The other way to do it is to use kubectl debug as follows:</p><pre>❯ kubectl debug node/test-cluster-worker -it --image ubuntu --profile sysadmin -- chroot /host bash<br>Creating debugging pod node-debugger-test-cluster-worker-4brfr with container debugger on node test-cluster-worker.<br>All commands and output from this session will be recorded in container logs, including credentials and sensitive information passed through the command prompt.<br>If you don&#39;t see a command prompt, try pressing enter.<br>root@test-cluster-worker:/# whoami<br>root</pre><p>Now edit and save the manifest at /etc/kubernetes/manifests/static-pod.yaml and add metadata.namespace: podinfo.<br>Once we add the namespace and try to get pods kubectl get pods we do not see the pod anymore! What does this mean?<br>The pod is still running on the node, but since the podinfo namespace does not exist, the kubelet cannot create a mirror pod in the api-server.<br>This causes the pod to be invisible to kubectl get pods (which queries the api-server), even though the container is still running on the node.</p><p>Now let’s create the namespace</p><pre>❯ kubectl create ns podinfo<br>namespace/podinfo created</pre><p>And now we check for pod in the namespace</p><pre>❯ kubectl -n podinfo get pods<br>NAME                          READY   STATUS    RESTARTS   AGE<br>podinfo-test-cluster-worker   1/1     Running   0          58s</pre><p>It becomes visible again because the mirror pod was successfully created.</p><h3>Conclusion</h3><p>Static pods are a core concept in Kubernetes clusters but they have the potential to create security risks. They can cause pods to become invisible to kubectl by referencing non-existent namespaces allowing attackers to remain hidden in the compromised Kubernetes cluster.</p><p>To detect this and other anomalies, always have auditing enabled on the Kubernetes cluster so that the administrators can track Kubelet and API Server activities. Additionally, regularly inspect Kubernetes node processes using kubectl debug node to catch unknown processes running on a node.</p><p>For more on attacker persistence strategies, see <a href="https://youtu.be/GtrkIuq5T3M">Rory McCune’s presentation</a>. To dive deeper into Kubernetes fundamentals, check out my <a href="https://anshumantripathi.com/blog/understanding-kubernetes">Kubernetes Concepts guide</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c41d46986979" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Container Logging: Best Practices for Docker and Kubernetes]]></title>
            <link>https://medium.com/@anshumantripathi/container-logging-7960ccf2419c?source=rss-27b7e6a4a92d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7960ccf2419c</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[containerization]]></category>
            <dc:creator><![CDATA[Anshuman Tripathi]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 08:27:05 GMT</pubDate>
            <atom:updated>2024-10-19T17:01:05.407Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Explore container logging best practices for Docker and Kubernetes. Learn about logging drivers, architectures, and strategies to enhance your application observability.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PPCTm9sS_zu296TxJAAbQ.png" /><figcaption>Container logging in Kubernetes</figcaption></figure><p>Logs are essential for the development and troubleshooting of containers. Containers utilize a specialized logging framework for various reasons, such as isolation, standardization, and managing scalability.<br>When a container starts, the container runtime (such as containerd, runc, cri-o, or docker) captures the standard output (stdout) and standard error (stderr) streams from the application running in the container. These logs are then written to a file, typically located at /var/log/&lt;docker/containerd/pod&gt;. This log directory can be mounted on the host system, allowing logs to be persisted and accessed even after the container stops. Various command-line tools, such as docker and nerdctl, can then read these log files to display the container’s logs to users.</p><h3>Logging in Docker</h3><p>Docker includes multiple logging mechanisms to help you get information from running containers and services. These mechanisms are called logging drivers. Docker uses logging drivers to manage specialized logging for containers. The default <a href="https://docs.docker.com/config/containers/logging/json-file/">json-file</a> logging drivers capture the standard output and standard error streams and write each log into a JSON format with the following structure:</p><pre>{<br>  &quot;log&quot;: &quot;Log line is here\n&quot;,<br>  &quot;stream&quot;: &quot;stdout&quot;,<br>  &quot;time&quot;: &quot;2019-01-01T11:11:11.111111111Z&quot;<br>}</pre><h3>Delivery Modes</h3><h4>Blocking Delivery</h4><p>A container in blocking mode — Docker’s default mode — will interrupt the application each time it needs to deliver a message to the driver. This guarantees that all messages will be sent to the driver, but it can have the side effect of introducing latency in the performance of your application; if the logging driver is busy, the container delays the application’s other tasks until it has delivered the message <a href="https://deploy-preview-35--anshumantripathi.netlify.app/blog/container-logging/#fn:2">2</a>.</p><p>The potential effect of blocking mode on the performance of your application depends on which logging driver you choose. For example, the json-file driver writes logs very quickly since it writes to the local file system, so it’s unlikely to block and cause latency. On the other hand, drivers that need to open a connection to a remote server—such as gcplogs and awslogs—are more likely to block for longer periods and could cause noticeable latency.</p><h4>Non-Blocking Delivery Mode</h4><p>In non-blocking mode, a container first writes its logs to an in-memory <a href="https://embedjournal.com/implementing-circular-buffer-embedded-c/#what-is-a-circular-buffer">ring buffer</a>, where they’re stored until the logging driver is available to process them. Even if the driver is busy, the container can immediately hand off the application output to the ring buffer and resume executing the application. This ensures that a high volume of logging activity won’t affect the application’s performance running in the container.</p><p>In contrast to the delivery mode, the non-blocking delivery mode does not guarantee that the logging driver will pick up all logs. <em>If the application emits logs faster than the driver can process, the ring buffer can overflow, leading to missing logs.</em> The max-buffer-size can be used to increase the ring buffer’s size to handle the logs’ parsing. The default value of max-buffer-size is 1 megabyte.</p><h3>Log Rotation</h3><p>By default, the support logging drivers do not support log rotation. This can increase disk usage for containers when using log drivers like json-file.</p><p>In such cases, it can be helpful to switch to <a href="https://docs.docker.com/config/containers/logging/local/">the </a><a href="https://docs.docker.com/config/containers/logging/local/">local logging driver</a>, which is optimized for performance and disk usage by support log rotation by default.</p><p>The local logging driver, unlike some other drivers, is optimized for performance and disk usage by supporting log rotation by default. When using the local driver, its default configuration preserves 100MB of log messages per container and uses automatic compression to reduce disk size. The default size of each log file is 20 MB. Once a log file reaches the 20 MB limit, a new file is created. By default, the local driver maintains 5 such files per container to handle log rotation.</p><h3>Logging in Kubernetes</h3><p>When containers are deployed to a Kubernetes cluster, they run inside a pod on a node. The container runtime is installed on the node, and the Kubelet process is responsible for managing all the containers on the node.</p><p>The container runtime handles and redirects all the logs generated by the containers through the stdout and stderr streams. Different container runtimes implement this differently; however, the integration with the kubelet is standardized as the CRI logging format.</p><p>The kubelet makes logs available to clients via a unique feature of the Kubernetes API. The usual way to access this is by running kubectl logs.</p><h4>Log Rotation in Kubernetes</h4><p>The Kubelet is responsible for rotating a container’s logs and managing the logging directory structure. It sends this information to the Container Runtime Interface (CRI) so that it can write logs to the given location.<br>The Kubelet’s containerLogMaxSize (default 10Mi) and containerLogMaxFiles (default 5) can be configured to manage log rotation. (<a href="https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/">Refer to Kubelet’s configuration arguments for more details</a>).</p><p>To perform an efficient log rotation in clusters where the volume of the logs generated by the workload is large, kubelet also provides a mechanism to tune how the logs are rotated in terms of how many concurrent log rotations can be performed and the interval at which the logs are monitored and rotated as required. You can configure two kubelet configuration settings, containerLogMaxWorkers and containerLogMonitorInterval, using the kubelet configuration file.</p><h3>Logging Architectures</h3><p>The following are the common logging patterns considered for collecting container logs:</p><ol><li>Use a node-level logging agent when it runs on every host.</li><li>Using a dedicated sidecar container with a logging agent.</li><li>Push logs directly from the container to the logging backend.</li></ol><p>Let’s explore each of the logging architectures in more detail.</p><h3>Using a node-level logging agent</h3><p>As mentioned above, a container collects logs and stores them in a directory structure that can be mounted on the host. Once the directory is mounted, a log collection agent can run on the host and access the log directories to collect and push logs to the logging backend. This is the most commonly used log aggregation architecture for containers.</p><p>In Kubernetes, a <a href="https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/">DaemonSet</a> can be used to run a log collector on each node which can access the logging directories and push the logs to a logging aggregator.</p><p>Node-level logging creates only one agent per node and doesn’t require any changes to the applications running on the node.</p><p>Some examples of log collectors include <a href="https://docs.datadoghq.com/containers/kubernetes/log/?tab=datadogoperator">Datadog</a>, <a href="https://grafana.com/docs/loki/latest/send-data/">Grafana</a>, <a href="https://www.fluentd.org/">Fluentd</a> and <a href="https://www.elastic.co/guide/en/beats/filebeat/current/running-on-kubernetes.html">Filebeat</a>.</p><h3>Using a sidecar container with a logging agent</h3><p>You can use a sidecar container that can be configured to run with the application container, which can do one of the following:</p><ul><li>The sidecar can stream the application logs to its stdout</li><li>The sidecar container can run a logging agent to scrape logs from the application container and push them to a log aggregator.</li></ul><p><a href="https://kubernetes.io/docs/concepts/cluster-administration/logging/#sidecar-container-with-logging-agent">Details about these approaches are explained excellently in the Kubernetes official documentation.</a></p><p>Using the sidecar-based approach has certain disadvantages.</p><ol><li>Using sidecar-based logging can be problematic for Jobs, where the sidecar can keep the container running.</li><li>Sidecars require additional CPU and memory usage.</li><li>If a sidecar is streaming an application’s logs to its own log stream, then it is not a good practice to stream different log streams into one stream. In this case, there would be a need to create different sidecars for different log streams.</li><li>If the sidecar container is scraping logs and running a logging agent to push the logs to the log aggregator, then fetching logs with kubectl logs will not work since the kubelet no longer manages logs.</li></ol><h3>Push logs directly from the container to the logging backend</h3><p>The containers can be configured to collect their logs and push them directly to the logging aggregator. This approach allows the application to control how the logs are moved to the logging aggregator. However, this approach comes with the caveat that the application needs to be integrated with a log scraping and pushing mechanism. This can make the application more complex and challenging to troubleshoot. Furthermore, fetching logs with kubectl logs will not work since logs are not managed by the kubelet.</p><p>Pushing logs directly from the container shifts the responsibility of log aggregation to the application itself. This approach can be beneficial in scenarios where an application requires custom log handling or needs to aggregate logs independently from the cluster-wide logging system. However, it’s important to consider the added complexity this method introduces to the application and its potential impact on maintainability.</p><h3>Conclusion</h3><p>Container logging is a crucial aspect of modern application development and management. We’ve explored various logging mechanisms in Docker and Kubernetes, from basic log capture to advanced architectures like node-level agents and sidecars. Each approach offers unique benefits and trade-offs in terms of performance, scalability, and ease of implementation.</p><p>As container environments continue to evolve, effective logging strategies become increasingly important for debugging, monitoring, and maintaining applications. Whether you choose to use node-level logging agents, sidecar containers, or direct log pushing, the key is to implement a solution that best fits your specific use case and infrastructure requirements.</p><p>By understanding these logging concepts and architectures, developers and operations teams can make informed decisions to enhance their container observability and streamline their troubleshooting processes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7960ccf2419c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Zanzibar — Google’s Consistent, Global Authorization System]]></title>
            <link>https://medium.com/@anshumantripathi/understanding-zanzibar-googles-consistent-global-authorization-system-7e7eeabe3859?source=rss-27b7e6a4a92d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e7eeabe3859</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[zanzibar]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Anshuman Tripathi]]></dc:creator>
            <pubDate>Mon, 05 Feb 2024 08:07:01 GMT</pubDate>
            <atom:updated>2024-10-19T16:26:38.716Z</atom:updated>
            <content:encoded><![CDATA[<h3>Google Zanzibar: Understanding the Global Authorization System</h3><h4>Explore Google’s Zanzibar, a high-performance global authorization system. Learn about its principles, data modeling, and consistency mechanisms.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*xYeJhYt3xKferMAMLucyZw.png" /><figcaption>Image generated from Dall-E</figcaption></figure><p>I have been reading about Zanzibar — Google’s Consistent, Global Authorization System, which is a Globally distributed authorization system capable of processing 10 million client queries per second with a latency of less than 10 milliseconds while having 99.99% availability¹. The following is a summarization of my understanding of Zanzibar. While some parts have been rephrased and reorganized to improve understanding, others have been taken verbatim from the paper.</p><h3>What is the need of a system like Zanzibar</h3><p>Creating a permissions system within an application can be complex. When a user creates permissions within an application to manage their content, this becomes even more challenging since these permissions become a core part of each request. As the system scales, so does the complexity of such a system, which creates security holes within the application, compromising the user content in your application².<br>For example, web-based photo storage services typically allow photo owners to share some photos with friends while keeping other photos private. Such a service must check whether a photo has been shared with a user before allowing that user to view the photo. Robust authorization checks are central to preserving online privacy¹.</p><h3>Principles of Zanzibar</h3><p>The Zanzibar authorization system works on the following principles¹</p><h4>Correctness</h4><ul><li>It must ensure consistency of access control decisions to respect user intentions.</li><li>Zanzibar supports global consistency of access control decisions through two interrelated features.</li><li>First, it respects the order in which ACL changes are committed to the underlying data store.</li><li>Second, it can ensure that authorization checks are based on ACL data no older than a client-specified change. Thus, for example, a client can remove a user from a group and be assured that subsequent membership checks reflect that removal.</li><li>Zanzibar provides these ordering properties by storing ACLs in a globally distributed database system with external consistency guarantees¹.</li></ul><h4>Flexibility</h4><p>It must support a rich set of access control policies as consumer and enterprise applications require.</p><blockquote>Groups can contain other groups, which illustrates one of the challenges facing Zanzibar.</blockquote><p>Group memberships are an essential class of ACL, where<br>the object is a group, and the relation is semantically equivalent to a member. Groups can contain other groups, which illustrates one of the challenges facing Zanzibar: evaluating whether a user belongs to a group can entail following a long chain of nested group membership¹.</p><h4>Low Latency</h4><p>It must respond quickly because authorization checks are often in the critical path of user interactions. Low tail latency is significant for serving search results, often requiring tens to hundreds of checks.</p><p>Zanzibar employs various techniques to achieve low latency and high availability in this globally distributed environment. Its consistency protocol allows most requests to be served with locally replicated data without requiring cross-region round trips. Zanzibar stores its data in normalized forms for consistency. It handles hot spots on normalized data by caching final and intermediate results and deduplicating simultaneous requests. It also applies techniques such as hedging requests and optimizing computations on deeply nested sets with limited denormalization¹.</p><h4>High Availability</h4><p>It must reliably respond to requests because client services would be forced to deny users access without explicit authorizations.</p><h4>Large Scale</h4><p>It needs to protect billions of objects shared by billions of users. It must be deployed around the globe to be near its clients and their end users.<br>Zanzibar responds to over 95% of authorization checks within 10 milliseconds and has maintained more than 99.999% availability for the last 3 years.</p><h3>Zanzibar Data modeling</h3><p>Zanzibar uses a simple but powerful data-modeling language that allows clients to define arbitrary relations between users and objects, such as owner, editor, commenter, and viewer. It includes set-algebraic operators such as intersection and union for specifying potentially complex access control policies regarding user-object relations. For example, an application can specify that users granted editing rights on a document are also allowed to comment on the document, but not all commenters are given editing rights.</p><h4>Relational Tuple</h4><p>Zanzibar uses <em>relational tuples</em>, the semantic representation of its ACL policies.<br>It can represented as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*Ft4mgec7iZ96VMyS9K7VOQ.png" /><figcaption>Relational tuples in Zanzibar</figcaption></figure><p>Lets a take a look at some parsed examples:</p><p>This is a very simple tuple which defines relation based of userId 10 having owner permission to object doc:readme</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2lPjuJ6PA_F_EhHiyupAA.png" /><figcaption>User `10` has `owner` access to `doc:readme`</figcaption></figure><p>In this example we define the relationship on the userId `11` as a `member` of `group:eng`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2lPjuJ6PA_F_EhHiyupAA.png" /><figcaption>User `10` is `owner` of theo object`doc:readme`</figcaption></figure><p>This is a complex example defining a chained relation. Notice how two usersets are linked to one another with `@`.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0CLzQ5X60HKBl_XRJY9-Q.png" /><figcaption>Members of `group:eng` have `viewer` access to `doc:readme`</figcaption></figure><h4>Consistency Model</h4><p>To maintain the consistency of changes to ACLs, Zanzibar must respect the order in which users modify the ACLs and object contents to avoid unexpected sharing of the data. The task here is to prevent the “new enemy” problem that can arise when the order in the permissions are read is not aligned with the order of changes in the permission. [Read more about the new enemy problem in the <a href="https://authzed.com/blog/new-enemies">Authzed Blog</a>]</p><p>Preventing the “new enemy” problem requires Zanzibar to understand and respect the causal ordering between ACL or content updates, including updates on different ACLs or objects and those coordinated via channels invisible to Zanzibar. Hence, Zanzibar must provide two fundamental consistency properties: external consistency, and snapshot reads with bounded staleness.</p><p>To maintain consistency across multiple transactions, Zanzibar adds a timestamp to causally related changes, i.e., changes that happen one after the other. With causally meaningful timestamps, any two changes x, y which occur one after the other such that their respective timestamps are T &lt; Ty , then any reads at or after Ty will include the changes done at Tx</p><p>Any reads happening in the Zanzibar system are done from a read snapshot, and to avoid applying old ACLs to new contents, the ACL check evaluation snapshot must not be staler than the causal timestamp assigned to the content update, which means any content update done at timestamp Tc , snapshot read one at any time ≥ Tc will include the changes done in Tc .</p><p>To avoid evaluating checks for new contents using stale ACLs, one could try to continually evaluate at the latest snapshot such that the check result reflects all ACL writes up to the check call. However, such evaluation would require global data synchronization with high latency round trips and limited availability¹.</p><p>The Zanzibar setup in Google uses Spanner to store ACLs to achieve this. <a href="https://cloud.google.com/spanner?hl=en">Google Cloud Spanner</a> is a globally available database with a TrueTime mechanism. Spanner assigns each version change with a microsecond resolvable timestamp to reflect the causal ordering of the changes. ACL check is done at a single snapshot timestamp across multiple database reads so that all writes with timestamp increment the check snapshot, and only those writes are visible to the ACL check.</p><p>Zanzibar follows the following protocol to allow checks to be evaluated on already replicated data:</p><ol><li>A Zanzibar client requests an opaque consistency token called a <em>zookie</em> for each content version when a content modification is about to be saved. Zanzibar encodes the current <em>global timestamp</em> and does an atomic write on the client machine to store the zookie. It should be observed that a content change check is only done when the content is changed. It needs to only happen once in the update transaction.</li><li>The client sends the zookie in subsequent ACL check requests to ensure the check snapshot is as latest as the content version’s timestamp.</li></ol><h4>Namespace Configuration</h4><p>Namespace configurations define relations of the ACL objects in Zanzibar. According to the Zanzibar’s research paper¹</p><blockquote>A namespace configuration specifies its relations as well as its storage parameters. Each relation has a name, a client-defined string such as viewer or editor, and a relation config. Storage parameters include sharding settings and an encoding for object IDs that helps Zanzibar optimize the storage of integer, string, and other object ID formats.</blockquote><p>This means a namespace defines how ACL object relations are defined and stored in Zanzibar.</p><p>For example, if a system has roles “Viewer,” “Editor,” and “Owner,.” If a user is defined as an owner, adding a relation tuple for all three roles is redundant and wasteful. Namespaces can rewrite the ACL policies based on these roles to improve this. Here is an example taken from the paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HENtb55kRcow-hGLTuqJHw.png" /><figcaption>An example of namespace where viewer contains editor and editor contains owner</figcaption></figure><ul><li>_this returns all the policies of the current role.</li><li>computed_userset computes the policies based on the relation defined within it.</li><li>tupe_to_userset computes a tupleset from the input object, fetches relation tuples matching the tupleset (a set of tuples with a given object_id which can be used to look up ACLs for a given object), and computes a userset from every fetched relation tuple.</li></ul><h4>API</h4><p>Zanzibar provides APIs for clients to read, write, modify, watch, check, and expand operations.<br>All these API methods use zookie in their request. A zookie is an <em>opaque</em> cookie that contains a globally meaningful timestamp and/or a client content version, and/or a read snapshot. A zookie is designed to be opaque so that clients cannot misuse a cookie by sending arbitrary timestamps.<br>Let’s take a closer look at each of these APIs</p><p><strong>Read</strong></p><p>For a read API, the client sends one or more tuplesets and an optional zookie containing a timestamp and a snapshot version.<br>With the zookie clients can request a read snapshot no earlier than the previous write operation. If the request does not contain the zookie, Zanzibar will choose a reasonably recent snapshot, which generally offers a lower latency response than if a zookie was provided.</p><p>It should be noted that read requests only depend on the content of the relation tuples and do not reflect userset rewrite rules. For example, even if the viewer userset always includes the owner userset, reading tuples with the viewer relation will not return tuples with the owner relation. Clients that need to understand the effective userset can use the <a href="https://anshumantripathi.com/blog/google-zanzibar-global-authorization-system-part-1/#expand">Expand API</a>.</p><p><strong>Write</strong></p><p>Zanzibar clients can use the write API to modify a relation tuple to add or remove an ACL. Clients can also modify all tuples related to an object using a read-modify-write process that uses a read RPC followed by a write RPC. This process works as follows:</p><ol><li>Read all relation tuples of an object, including a per-object “lock” tuple.</li><li>Generate the tuples to write or delete. Send the writes, along with a touch on the lock tuple, to Zanzibar, with the condition that the <em>writes will be committed only if the lock tuple has not been modified since the read</em>. A touch is being used on the lock tuple to make sure the access time on the lock tuple is updated.</li><li>If the write condition is not met, go back to step 1.</li></ol><p><strong>Watch</strong></p><p>A watch request specifies one or more namespaces and zookie representing the time to start watching. A watch response contains all the tuple modification events in ascending timestamp order from the requested start timestamp to a timestamp encoded in a heartbeat zookie included in the watch response. The client can use the heartbeat zookie to repeatedly call on the watch API to resume watching where the previous watch response was left off.</p><p><strong>Check</strong></p><p>Like reads, a check is evaluated at a consistent snapshot no earlier than the given zookie.<br>To authorize application content modifications, our clients send a special check request, a content-change check. A content-change check request does not carry a zookie and is evaluated at the latest snapshot. If a content change is authorized, the check response includes a zookie for clients to store along with object contents and use for subsequent checks of the content version. The zookie encodes the evaluation snapshot and captures any possible causality from ACL changes to content changes because the zookie’s timestamp will be greater than that of the ACL updates that protect the new content.</p><p><strong>Expand</strong></p><p>Unlike the Read API, Expand follows indirect references expressed through userset rewrite rules. The result is represented by a userset tree whose leaf nodes are user IDs or usersets pointing to other object relation pairs, and intermediate nodes represent union, intersection, or exclusion operators. Expand is crucial for our clients to reason about the complete set of users and groups with access to their objects, allowing them to build efficient search indices for access-controlled content.</p><blockquote>Continue reading about Zanzibar Architecture and Implementation in the next Part - <a href="https://anshumantripathi.com/blog/zanzibar-architecture-implementation-part-2/">Zanzibar Architecture and Implementation: Google’s Authorization Solution</a></blockquote><h3>References</h3><ol><li><a href="https://research.google/pubs/zanzibar-googles-consistent-global-authorization-system/">https://research.google/pubs/zanzibar-googles-consistent-global-authorization-system/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e7eeabe3859" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Kubernetes]]></title>
            <link>https://medium.com/@anshumantripathi/understanding-kubernetes-a51656629a18?source=rss-27b7e6a4a92d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a51656629a18</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[cloud-services]]></category>
            <dc:creator><![CDATA[Anshuman Tripathi]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 19:38:06 GMT</pubDate>
            <atom:updated>2023-09-17T19:42:29.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ClWmdNqZHdJT1s9nUy9Gw.png" /><figcaption><a href="https://kubernetes.io/blog/2023/08/15/kubernetes-v1-28-release/">Official Logo of Kubernetes 1.28 (Platernetes)</a></figcaption></figure><p>Kubernetes has become an essential tool in the Software Engineering industry. Everyone wants to use it, and most times, we successfully make it work, but it suddenly becomes the occult when it does not work the way we think it should. Let us take a moment to understand how it works and how to use it to deploy applications seamlessly.<br>So, what is Kubernetes? As <a href="https://kubernetes.io/">official documentation mentions, it allows you to do “Production-Grade Container Orchestration”</a>, but does this mean? Well, let’s take a step back. At this point, I hope you understand what a container is (if not, refer <a href="https://www.anshumantripathi.com/blog/containers">to my other post explaining containers</a>), but in short, a container to run a process in isolation, allowing you as an application developer to create an image for your application and have <em>some confidence</em> that it is going to run the same way on every environment as it runs on your machine. Many tools allow you to create an image for your application and spin a container from it, such as Podman, containerd, cri-o, Docker, etc. (Anyone who has been working in the software development industry within the last five years should’ve atleast heard of Docker).<br>Now that you have a container for your application, you can use this image to deploy to production, but we still need to figure out</p><ol><li>Where is this container going to run?</li><li>How is the underlying infrastructure set up?</li><li>How is the network stack set up?</li><li>If there is a surge or drop in my application’s traffic, how can we efficiently scale up or down?</li><li>How do you manage configurations and secrets used by your application?</li></ol><p>Creating containers is easy and reproducible, but there is still a lot to figure out on handling issues like the ones mentioned above. All of these issues fall into <em>orchestration</em>. Kubernetes can help you manage all of these problems in a scalable manner.</p><h3>Understanding Kubernetes</h3><p>Let’s look at the different kinds of components available in Kubernetes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgCQaO_qHfzRWE2sP88UGA.png" /><figcaption>Elements in Kubernetes</figcaption></figure><p><a href="https://kubernetes.io/docs/concepts/workloads/pods/">Pods</a> are the smallest deployable units of computing that you can create and manage in Kubernetes. Pods can hold one or more containers, and they define the specifications of executing the containers. A Pod is similar to a set of containers with shared namespaces and shared filesystem volumes. <a href="https://www.anshumantripathi.com/blog/containers">Read more Linux containers in my other blog post.</a></p><h3>Control Plane</h3><p>A Kubernetes control plane is a collection of services that manage all operations and elements on the worker plane in the Kubernetes cluster. It can be thought of as the brains of the Kubernetes cluster. To understand how Kubernetes works under the hood, it is vital to know how the control plane functions. Services like GKE (Google Kubernetes Engine), EKS (Elastic Kubernetes Service), and AKS (Azure Kubernetes Service) provide Kubernetes clusters where the cloud providers manage the control plane so the developers can focus on their application rather than addressing the Kubernetes infrastructure. The key elements of the control plane are as follows:</p><h4>API Server</h4><p>The API server exposes the Kubernetes API, which is required to interact with the Kubernetes cluster. The main implementation of a Kubernetes API server is kube-apiserver. kube-apiserver is designed to scale horizontally — that is, it scales by deploying more instances. <a href="https://kubernetes.io/docs/concepts/overview/components/#kube-apiserver">You can run several instances of kube-apiserver and balance traffic between those instances</a>.<br>When using private clusters with cloud-provided services like GKE, AKS, and EKS, accessing the API cluster would require setting up VPC peering and opening the required firewall rules because the control plane will run the cloud provider’s VPC.</p><h4>etcd</h4><p><a href="https://etcd.io/">etcd is a distributed and reliable key-value store</a>. etcd in the control stores all the cluster data, including the cluster state. When using an on-prem Kubernetes cluster, always remember to setup a backup strategy for your Kubernetes etcd data store.</p><h4>Scheduler</h4><p><a href="https://kubernetes.io/docs/concepts/overview/components/#kube-scheduler">The Kubernetes scheduler monitors newly created pods with no assigned nodes</a>. It selects the node to run the pods on by considering resource requirements, controller type of the pod, node affinity/anti-affinity, data locality, hardware/software policy constraints, inter-workload interface, and deadlines. kube-scheduler is the implementation of the Scheduler.</p><h4>kube-proxy</h4><p>Kubernetes pods are ephemeral, so IP addresses cannot be relied upon for sending requests to a container inside a pod. kube-proxy solves this problem by maintaining network rules on every Kubernetes node, which allows network communication to the pods from network sessions. kube-proxy uses the operating system packet filtering layer if there is one and it’s available. Otherwise, kube-proxy forwards the traffic itself.<br>As the size of the Kubernetes clusters increases, and the number of nodes increases, the size of IP tables managed by kube-proxy also increases exponentially because it needs to kube-proxy running on every node to control the routing rules of pods running on all the other nodes. Using network policies like <a href="https://docs.tigera.io/">Calico</a> can help scale up a Kubernetes cluster.</p><h4>kube-dns</h4><p>kube-DNS is a DNS server running on the Kubernetes cluster. It is responsible for resolving DNS names for pods and services. kube-dns also provides caching for DNS queries to improve performance. Kublet configures the pod’s DNS so containers can lookup Services by name rather than IP. <a href="https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/">See Kubernetes documentation for more details on Kubernetes DNS addons.</a></p><h4>Controller Manager</h4><p>The controller manager is the component that runs all the controller processes. Logically, each controller is a separate process, but to reduce complexity, they are all compiled into a single binary and run in a single operation.</p><p>There are many types of controllers. Some examples of them are:</p><p><strong>Node controller</strong>: Responsible for noticing and responding when nodes go down.<br><strong>Job controller</strong>: Watches for Job objects that represent one-off tasks, then creates Pods to run those tasks to completion.<br><strong>EndpointSlice controller</strong>: Populates EndpointSlice objects (to provide a link between Services and Pods).<br><strong>ServiceAccount controller</strong>: Create default ServiceAccounts for new namespaces.<br>The above is a partial list.</p><h4>Cloud Controller Manager</h4><p>Cloud controller manager is an extension of the controller manager, which every cloud provider implements based on their infrastructure setup to provide services like GKE, EKS, and AKS.</p><h4>Kubelet</h4><p>The kubelet is the primary “node agent” that runs on each node. It can register the node with the api-server using one of the hostname, a flag to override the hostname, or specific logic for a cloud provider. <a href="https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet/">A kubelet is setup and managed by the Kubernetes administrator or the Cloud Provider of the managed Kubernetes service</a>.</p><h4>Nodes</h4><p>Nodes are instances that physically (or virtually) support the execution of instances. All nodes are managed by the control plane to manage pod scheduling. Each node has a kubelet process running on it, which connects to the control plane and registers itself. <a href="https://kubernetes.io/docs/concepts/architecture/nodes/">Nodes can be managed individually or through a node pool.</a></p><h3>Worker Plane</h3><h4>Namespaces</h4><p>Namespaces in Kubernetes provide a mechanism for isolating groups of resources within the cluster. Names of resources have to be unique within the namespace but not across namespaces. These are similar to <a href="https://www.anshumantripathi.com/blog/containers/#linux-namespaces">namespaces within Linux</a></p><h4>Deployment</h4><p>A Kubernetes deployment defines the desired state of a stateless application. <a href="https://kubernetes.io/docs/concepts/workloads/controllers/deployment/">A deployment manages replicasets, which in turn control pods</a>. Deployments can allow you to:</p><ol><li>Rollout updates to your pods.</li><li>Rollback changes to your pods.</li><li>Scale up or down to facilitate more loads.</li><li>Pause the rollout of your deployments.</li><li>Clean up old replicasets that are not needed anymore.</li></ol><h4>ReplicaSets</h4><p>A ReplicaSet aims to maintain a stable set of replica Pods running at any given time. As such, it is often used to guarantee the availability of a specified number of identical Pods. A ReplicaSet is defined with fields, including a selector that selects how to identify Pods it can acquire, several replicas indicating how many Pods it should maintain, and a pod template specifying the data of new Pods it should create to meet the number of replicas criteria. A ReplicaSet then fulfills its purpose by creating and deleting Pods as needed to reach the desired number. When a ReplicaSet needs to create new Pods, it uses its Pod template.<br><a href="https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/">It is recommended to use deployments to manage pods through replicasets.</a></p><h4>StatefulSets</h4><p><a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/">StatefulSet manages the deployment and scaling of a set of pods and guarantees the ordering and uniqueness of these pods.</a><br>Like a Deployment, a StatefulSet manages Pods based on an identical container spec. Unlike a Deployment, a StatefulSet maintains a sticky identity for each of its Pods. These pods are created from the same spec but are not interchangeable: each has a persistent identifier maintained across rescheduling.<br>If you want to use storage volumes to provide persistence for your workload, you can use a StatefulSet as part of the solution. Although individual Pods in a StatefulSet are susceptible to failure, the persistent Pod identifiers make it easier to match existing volumes to the new Pods that replace any that have failed.<br>StatefulSets currently requires a <a href="https://www.anshumantripathi.com/blog/understanding-kubernetes/#headless-services">Headless Service</a> to be responsible for the network identity of the Pods. You are responsible for creating this Service.</p><h4>CronJobs</h4><p>CronJobs are used to create jobs at regular intervals. CronJobs are helpful when creating jobs like scheduled backups, cleanups, report generation, etc. One CronJob object is like one line of a crontab (cron table) file on a Unix system. It runs a job periodically on a given schedule, written in Cron format. CronJobs have limitations and idiosyncrasies. For example, a single CronJob can create multiple concurrent Jobs in certain circumstances. <a href="https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/#cron-job-limitations">Before using a CronJob, always be sure to check for CronJob limitations in the official Kubernetes documentation.</a></p><h4>Jobs</h4><p>A Job creates one or more pods that retries execution until a specified number of them successfully terminate based on a cron schedule. As the pods are complete, the Job keeps track of the status of execution and termination of the respective pods.</p><h3>Configurations</h3><h4>ConfigMap</h4><p>ConfigMap is a way to decouple non-sensitive configurations from your application containers. A ConfigMap provides a way to mount the configurations of the configmap as a volume to the container. <a href="https://kubernetes.io/docs/concepts/configuration/configmap/">It should be remembered that a ConfigMap is supposed to hold a manageable amount of data</a>. A ConfigMap is limited to using 1 MiB of data. Adding different volumes to the container is better if you need more data. It should also be remembered that changes to configmap do not automatically get reflected in the pod. To allow the pod to see the changes in the configmap, the controller needs to rollout restart so that the updated configmap can be mounted on the new pods.</p><h4>Secrets</h4><p>Secrets are a way to store a small amount of sensitive data and decouple them from your application container. This way, an application can reference decoupled secrets from the container.<br>A Kubernetes holds data in base64 encoded format and <em>are not encrypted</em> and stored in plain text in the etcd in the Kubernetes control plane. Anyone with API access can access all the secrets. To make sure the secrets are secure, consider using the following:</p><ol><li>Encryption at rest in the cluster.</li><li>Restrict API access and external etcd reads from the control plane.</li><li><a href="https://secrets-store-csi-driver.sigs.k8s.io/concepts.html#provider-for-the-secrets-store-csi-driver">Consider using external secret providers like Vault.</a></li></ol><h3>Authorization</h3><h4>Roles</h4><p>Roles are <em>namespace-bound</em> objects in Kubernetes that define rules for a set of Kubernetes APIs. These permissions are purely additive, i.e., no deny rules exist. With RoleBindings, a group of permissions can be defined for users to access resources within a namespace.</p><h4>RoleBindings</h4><p>RoleBindings are <em>namespace-bound</em> objects used to assign a role to a subject, which can be users, groups, or service accounts.</p><h4>ClusterRoles</h4><p>ClusterRoles are <em>cluster-bound</em> objects that, like Roles, define rules for a set of Kubernetes APIs. Although ClusterRoles are cluster-bound, cluster roles can bind permissions to specific namespaces with RoleBindings.</p><h4>ClusterRoleBindings</h4><p>ClusterRoleBindings are <em>cluster-bound</em> objects that tie ClusterRoles to subjects (users, groups, or service accounts). These permissions are used to set the permissions of the subjects across the cluster, i.e., across all namespaces.</p><h3>Storage</h3><h4>Persistent Volumes and Persistent Volume Claims</h4><p><a href="https://www.anshumantripathi.com/blog/k8s-persistent-volumes">Read more about Persistent Volumes on my other post</a></p><h3>Fault Tolerance</h3><h4>PodDisruptionBudget</h4><p>A pod disruption event happens when, for some reason, pods disappear or are unable to get scheduled on nodes. This can be because of involuntary disruption (hardware failures, accidental deletion of VMs by cluster admins, a kernel panic, eviction of a pod because of the node running out of resources, etc.) or voluntary disruptions (draining a node for repair or upgrades, updating pod’s deployment pod template causing a restart, etc.).<br>PodDisruptionBudgets (PDBs) handle these disruptive events by specifying the minimum of pods to always be available during these events. A PDB limits the number of Pods of a replicated application that are down simultaneously from voluntary disruptions. For example, a quorum-based application would like to ensure that the number of replicas running is kept above the number needed for a quorum.</p><h3>Autoscaling components</h3><h4>Cluster Autoscaler</h4><p>Kubernetes cluster autoscaler is a Kubernetes component that adjusts the Kubernetes cluster size so that all the pods can be appropriately scheduled on the Kubernetes nodes.</p><h4>Horizontal Pod Autoscaler</h4><p>Horizontal Pod Autoscaler (HPA) is used to scale up the number of pods based on CPU and memory metrics.</p><h4>Vertical Pod Autoscaler</h4><p>Vertical Pod Autoscaler (VPA) is the component that scales the available CPU and memory of Kubernetes nodes based on the consumption of CPU and memory of the existing pods.</p><h3>Networking</h3><h4>Services</h4><p>Kubernetes services allow a way to expose your application running in one or more pods. Using a service allows a set of pods to accept any incoming traffic. As each pod gets its IP address, defining a route to a service running in multiple pods can be tricky since a controller-like deployment can restart and replace pods often, which is where a Service comes into the picture. Using a Service, developers do not need to worry about the changing IP address of the pods.<br>A service can provide mechanisms for traffic management and load balancing across the different application pods.</p><h4>Headless services</h4><p><a href="https://kubernetes.io/docs/concepts/services-networking/service/#headless-services">Sometimes, you don’t need load-balancing and a single Service IP. In this case, you can create headless Services by explicitly specifying </a><a href="https://kubernetes.io/docs/concepts/services-networking/service/#headless-services">None for the cluster IP address (</a><a href="https://kubernetes.io/docs/concepts/services-networking/service/#headless-services">.spec.clusterIP).</a></p><h4>Endpoints and EndpointSlices</h4><p><a href="https://kubernetes.io/docs/concepts/services-networking/service/#endpointslices">In the Kubernetes API, an Endpoints (the resource kind is plural) defines a list of network endpoints, typically referenced by a Service to define which Pods the traffic can be sent to.</a><br>Kubernetes’ EndpointSlice API provides a way to track network endpoints within a Kubernetes cluster. EndpointSlices offer a more scalable and extensible alternative to Endpoints.</p><h4>NetworkPolicies</h4><p>NetworkPolicies provide a way for traffic management and routing at the L3 and L4 (Network and Transport layer of the OSI network model). NetworkPolicies are an application-centric construct allowing you to specify how a pod can communicate with various network “entities”.</p><h4>Ingress</h4><p>Ingress defines how external traffic is accepted and routed in the cluster. Ingress may provide load balancing, SSL termination, and name-based virtual hosting. There are more sophisticated ingress solutions available which extend the feature of the Kubernetes ingress like <a href="https://istio.io/latest/docs/tasks/traffic-management/ingress/">Istio</a>, <a href="https://www.getambassador.io/docs/edge-stack/latest/topics/running/ingress-controller">Ambassador</a> and <a href="https://doc.traefik.io/traefik/providers/kubernetes-ingress/">Traefik</a>.</p><blockquote>Read more about other topics - <a href="https://www.anshumantripathi.com/blog/">https://www.anshumantripathi.com/blog/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a51656629a18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bloom Filters]]></title>
            <link>https://medium.com/@anshumantripathi/bloom-filters-c1c3ef064942?source=rss-27b7e6a4a92d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1c3ef064942</guid>
            <category><![CDATA[bloom-filter]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Anshuman Tripathi]]></dc:creator>
            <pubDate>Sun, 21 May 2023 23:59:54 GMT</pubDate>
            <atom:updated>2024-11-10T21:26:29.116Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>See the implementation of Bloom Filters in Python here — <a href="https://www.anshumantripathi.com/blog/bloom-filter/#implementing-a-bloom-filter">https://www.anshumantripathi.com/blog/bloom-filter/#</a>implementation</blockquote><p>A bloom filter is a <em>space efficient</em> probabilistic data structure that can be used to determine the membership of an element in a given set. In other words, <strong>a bloom filter in itself does not store the elements but only keeps a probabilistic record of the existence of an element in the set.</strong> A bloom filter uses an array of bits to determine a value’s membership, making it far more space efficient than other data structures like trees.<br>Space efficiency is a trade-off when using bloom filters because a bloom filter is probabilistic, i.e., a bloom filter can give some amount of false positives. In other words, a bloom filter can return true for a value that might not belong to the given set. However, a bloom filter does not have false negatives, i.e., it never returns false for a value that exists because it only allows read and writes but not deletes.<br>The rate of false positives can be calculated with the following formula¹</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*eCMny9QBuPfC2VDuJyks8Q.png" /><figcaption>Rate of false positives in a bloom filter.</figcaption></figure><p>where,<br>f = the false positive rate<br>m = number of bits in a Bloom filter<br>n = number of elements to insert<br>k = number of hash functionsThis is a significant factor in deciding whether a bloom filter should be used.</p><h3>How to use effectively use Bloom filters</h3><p>The efficiency of bloom filters relies on using the right setting for bits per element (<em>m</em>/<em>n</em>) and the number of hash functions(<em>k</em>). A higher number of bits per element, like 8–10 with 2–3 hash functions, can create a bloom filter with false-positive rates of &lt;1%¹.<br>Increasing the number of hash functions might not always result in a reduced false positive rate. Furthermore, a bloom filter with many hash functions will have a higher complexity of insertion, reducing the time complexity. On the other hand, increasing the number of bits per element means the bloom filter takes more storage space which can defeat the whole purpose of using a bloom filter. It is vital to use discretion when setting the values of m, n, and k for the bloom filter.</p><h3>Other considerations for using a bloom filter</h3><p>A bloom filter does not allow deletions. Other variations of bloom filters like <a href="https://en.wikipedia.org/wiki/Counting_Bloom_filter">Counting Bloom Filters</a> support deletion, but they also introduce probabilities of false negatives.</p><p>Unlike Hashmaps, once a bloom filter is created, it isn’t easy to scale it. In hashmaps, the map size can be increased based on the doubling function, and the entries can be rehashed. Since the bloom filter does not store the values (or any reference to actual values), scaling up a bloom filter can mean recreating the whole filter, which would lose all the original values.</p><p>Also, Bloom filters are vulnerable when the queries are not drawn uniformly and randomly. Queries in real-life scenarios are rarely uniformly random. Instead, many queries follow the Zipfian distribution, where a small number of elements is queried many times, and a large number of elements is queried only once or twice. This pattern of queries can increase our effective false positive rate if one of our “hot” elements, i.e., the elements often queried, results in a false positive¹.</p><h3>References</h3><ol><li><a href="https://freecontent.manning.com/all-about-bloom-filters/">https://freecontent.manning.com/all-about-bloom-filters/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1c3ef064942" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Commit signing]]></title>
            <link>https://medium.com/@anshumantripathi/commit-signing-1b68f81d0b31?source=rss-27b7e6a4a92d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b68f81d0b31</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-supply-chain]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Anshuman Tripathi]]></dc:creator>
            <pubDate>Tue, 09 May 2023 02:59:18 GMT</pubDate>
            <atom:updated>2023-05-12T22:03:59.688Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Secure your code repositories by signing your commits.</em></p><h3>What is commit signing</h3><p>Signing a commit means adding a cryptographic hash which can be only generated through the author’s private key (called “signature”), thus verifying the identity of the author of the commit. To sign a commit, a developer uses a <a href="https://gnupg.org/">GPG (GNU Privacy Guard) key</a>. GPG allows you to encrypt and sign your data and communications; it features a versatile key management system and access modules for all kinds of public key directories.<br>When an author creates a GPG signature, it is generated as a combination of a private key and a public key, the private key is saved on the author’s computer, and the public key is shared with the version control system, which uses the public key to verify the commits which contain a hash generated using the private key.</p><h3>Why you should sign a git commit</h3><h3>Avoid impersonations</h3><p>If an author does not sign their commits, it becomes simple to impersonate them. Anyone who has access to contribute to a repository can update git config user.email and git config user.name to the details of the author who does not sign their commits impersonating the author.<br>You can avoid impersonations when you sign commits; as a commit can only be signed by the author’s private key (or someone with the author’s private key), a signed commit becomes proof that the author made the commit from the commit details. Programs like GPG provide a way to generate and manage keys (signatures) and sign commits only after entering a signing password, making using a compromised private key difficult. When you habitually sign all your commits, an unsigned commit can be flagged as an impersonation for further investigation.</p><h3>Secure repository against malicious changes</h3><p>Suppose an attacker tries to impersonate a repository collaborator who has been making regular stable updates. In that case, the attacker can create a pull request (or a merge request) impersonating an author, increasing the odds of getting approval on the code changes.</p><h3>Safety against supply chain attacks</h3><p>A supply chain attack is a cyber-attack where an attacker targets a company or organization’s supply chain, including all the vendors, suppliers, and contractors the organization relies on to conduct its operations.<br>In a supply chain attack, a malicious user can insert code and backdoor vulnerabilities in open-source libraries and packages used in applications in different companies. When the companies update their code to use the updated libraries, the attacker exploits the vulnerabilities and attacks the applications.<br>In other instances, a disgruntled employee who knows internal libraries and packages used by an application creates a replica in open source with the same name with a newer version. When a company uses a mix of internal libraries and open-source code, the package managers pull in code from open-source instead of the internal repositories, which inject applications with malicious code.</p><p>When a repository enforces signing commits, it provides authenticity that all the code in the repository comes from accepted collaborators. Having commit signing enforced in the repository, which provides critical features, ensures the repository is compromised with a supply chain attack.</p><h3>The verification badge</h3><p>A signed commit shows up with the Verified badge in the source control system.</p><figure><img alt="Verified badge commit with a signed commit" src="https://cdn-images-1.medium.com/max/1024/1*ZODzNscVMAjLg_rSmnl2rg.jpeg" /><figcaption>Verified badge with a signed commit.</figcaption></figure><blockquote>Read more about how to sign your commits here — <a href="https://www.anshumantripathi.com/blog/commit-signing/#how-to-sign-commits-with-github">https://www.anshumantripathi.com/blog/commit-signing/#how-to-sign-commits-with-github</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b68f81d0b31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Persistent Volumes in Kubernetes]]></title>
            <link>https://medium.com/@anshumantripathi/persistent-volumes-in-kubernetes-f9ab6e64483?source=rss-27b7e6a4a92d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9ab6e64483</guid>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Anshuman Tripathi]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 06:48:08 GMT</pubDate>
            <atom:updated>2023-03-21T06:54:15.451Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding the basics of Persistent volumes in Kubernetes.</em></p><p>Kubernetes provides ephemeral and persistent storage options for an application. Ephemeral storage like an emptyDir lives and dies with the pod, i.e., if the pod is deleted, all the data in the emptyDir is deleted. On the other hand, persistent storage is not coupled with the pod’s lifecycle. It requires understanding what kind of storage is needed and how to provision it (dynamically or statically).</p><p>Before we delve into what kind of storage is supported and how it is provisioned, let’s look into how Kubernetes abstracts the storage of your application using persistent volumes and persistent volume claims.</p><h3>Persistent Volumes (PV)</h3><p>A persistent volume is an object that represents a valid singular external storage. The kind of storage supported by the PV is defined by the administrator using a <a href="https://www.anshumantripathi.com/blog/k8s-persistent-volumes/#storage-classes">storage class</a> and can be NFS or cloud provider-supported persistent disks like AWS EBS, GCP PD, Azure Disk, etc.</p><h3>Persistent Volume Claims (PVCs)</h3><p>A persistent volume claim is a request made by a pod for PV. A pod can request a PV through a PVC for specific sizes and access modes like ReadWriteOnce, ReadWriteOncePod, ReadOnlyMany, or ReadWriteMany.</p><ol><li>A PV represents a single external storage, i.e., a PV and an external storage have a 1:1 relationship. A 100G external storage can only be divided across two PV objects for 50G each if the administrator divides the external storage into different volumes, in which case a PV points to a specific volume in the external storage.</li><li>A pod and a PVC have a 1:1 relationship. A pod requires a PVC to get the necessary external storage. Once a PVC is granted, the allocated persistent storage can be mounted to the pod as a volume.</li><li>A PV and a PVC can have a one-to-many relationship, i.e., multiple PVCs, and claim a specific PV as long as the total PVC size does not exceed the size of the PV.¹</li></ol><h3>Access Modes</h3><h4>ReadWriteOnce</h4><ul><li>A PV can be mounted as a volume on pods on the same nodes.</li><li>In this case, a single PV can be bound by multiple PVCs, given the pods raising a PVC are on the same node.</li></ul><h4>ReadWriteOncePod</h4><ul><li>A PV can be mounted as a volume on a single pod.</li><li>In this case, a single PV can only be bound by a single PVC. This access mode was introduced in Kubernetes version 1.22+.</li><li>Read more about it here — <a href="https://kubernetes.io/blog/2021/09/13/read-write-once-pod-access-mode-alpha/">https://kubernetes.io/blog/2021/09/13/read-write-once-pod-access-mode-alpha/</a>.</li></ul><h4>ReadOnlyMany</h4><ul><li>A PV can be mounted as volume as read-only for multiple nodes.</li><li>In this case, a single PV can be bound by multiple PVCs</li></ul><h4>ReadWriteMany</h4><ul><li>A PV can be mounted as volume for reading and writing for multiple nodes.</li><li>In this case, a single PV can be bound by multiple PVCs.</li><li>This mode is only supported by NFS external storage.</li></ul><h3>PV provisioning</h3><h4>Static</h4><ul><li>In this case, an external storage volume is manually pre-created by the administrator, and the PV points to the pre-created storage object.</li><li>PVs are explicitly declared to point to the existing pre-created storage objects.</li></ul><h4>Dynamic</h4><ul><li>The external storage object is dynamically created with the PV.</li><li>This provisioning is based on <a href="https://www.anshumantripathi.com/blog/k8s-persistent-volumes/#storage-classes">storage classes</a>. A PVC must mention the required storage class defined by the administrator.</li><li>PVCs with &quot; as storage classes have dynamic provisioning disabled.</li></ul><h3>Storage Classes</h3><p>A storage class is a way for Kubernetes administrators to define the types of storage which can be dynamically provisioned. A storage class can have the following properties:</p><h3>Volume Binding Mode</h3><p>The volumeBindingMode defines what kind of volume binding the PV supports. There are two types of supported volume binding modes:</p><h4>Immediate (default)</h4><ul><li>Immediate volume binding mode indicates volume binding, and dynamic provisioning of the PV happens when the PVC is created.</li><li>For storage backends that are topology-constrained and not globally accessible from all Nodes in the cluster, PersistentVolumes will be bound or provisioned without knowledge of the pod’s scheduling requirements, resulting in unschedulable Pods. <a href="https://www.anshumantripathi.com/blog/k8s-persistent-volumes/#fn:2">2</a></li></ul><h4>Wait For First Consumer (Recommended)</h4><ul><li>WaitForFirstConsumer will delay the volume binding and the dynamic provisioning until a pod using the PVC is created.</li><li>PersistentVolumes will be selected or provisioned conforming to the topology specified by the pod’s scheduling constraints. These include, but are not limited to, resource requirements, node selectors, pod affinity and anti-affinity, and taints and tolerations. <a href="https://www.anshumantripathi.com/blog/k8s-persistent-volumes/#fn:2">2</a></li></ul><h3>ReclaimPolicy</h3><p>Once the user is done with the PV, the PVC can be deleted so that the cluster can reclaim the PV. How the reclaim is done is defined by a ReclaimPolicy in the storage class.</p><h4>Retain</h4><p>The Retain reclaim policy allows the administrator to reclaim the PV manually. When a PVC with the “retain” reclaim policy is deleted, the PV is not deleted by the cluster. PV is marked as “released” but is not yet available for another claim because it contains all the data from the last PVC. To clean up this PV, the administrator must:</p><ol><li>Delete the PV object from the cluster. <strong>Note:</strong> This does not delete the external storage infrastructure (AWS EBS, GCP PD, Azure Disk) that the PV pointed to, which still contains all the data.</li><li>Manually clean up the data on the storage infrastructure.</li><li>Delete the storage infrastructure.</li></ol><p>If you want to reuse the same storage asset, create a new PersistentVolume with the same storage asset definition.</p><h4>Delete (Default)</h4><p>Delete is the default reclaim policy of the PV. In this case, once the PVC is deleted, its associated external storage is also cleaned up.</p><h3>Provisioners</h3><p>Provisioners define what volume plugin can be used to create the PV. They are of two categories:</p><h4>Internal provisioners</h4><ul><li>An internal provisioner is prefixed with kubernetes.io.</li><li>Internal provisioners are also referred to as in-tree provisioners because these <a href="https://github.com/kubernetes/kubernetes/tree/fe91bc257b505eb6057eb50b9c550a7c63e9fb91/pkg/volume">provisioners are defined in the Kubernetes Github repo</a>.</li><li><a href="https://kubernetes.io/docs/concepts/storage/storage-classes/#provisioner">Common internal provisioners can be found in the Kubernetes documentation.</a></li><li>Example: NFS does not provide an internal provisioner, but an external provisioner can be used.</li></ul><h4>External Provisoiners</h4><ul><li>External provisioners are third-party volume plugins.</li><li>These plugins are often implemented using the <a href="https://kubernetes.io/blog/2019/01/15/container-storage-interface-ga/">Container Storage Interface (CSI)</a>.</li></ul><h3>Parameters</h3><p>Each provisioner requires a set of parameters to set up the cluster’s storage.</p><h3>Mount options</h3><p>Mount options for the volume can be added if the provisioner plugin supports them.</p><h3>References</h3><ol><li><a href="https://www.digihunch.com/2021/06/kubernetes-storage-explained/">https://www.digihunch.com/2021/06/kubernetes-storage-explained/</a></li><li><a href="https://kubernetes.io/docs/concepts/storage/storage-classes/#volume-binding-mode">https://kubernetes.io/docs/concepts/storage/storage-classes/#volume-binding-mode</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9ab6e64483" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monoliths or Microservices?]]></title>
            <link>https://medium.com/@anshumantripathi/monoliths-or-microservices-77a8e94b6911?source=rss-27b7e6a4a92d------2</link>
            <guid isPermaLink="false">https://medium.com/p/77a8e94b6911</guid>
            <category><![CDATA[monolith]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Anshuman Tripathi]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 01:37:54 GMT</pubDate>
            <atom:updated>2023-03-06T17:26:06.820Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Are microservices perfect?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tv7g-YS8b970R5eryvdqdw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/ko/@diesektion?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Robert Anasch</a> on <a href="https://unsplash.com/photos/SPHz3KKquKk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The phrase <em>microservices</em> is known to everyone, even to someone uninitiated in software engineering, but what do microservices actually mean, and why are they suddenly in such demand? Let’s delve deeper.</p><h3>Microservices</h3><ul><li>Microservices divide software components into different, loosely coupled, individually deployable, and runnable services. Since the ownership of individual services can be divided amongst other teams, these services are also split into different version-controlled repositories.</li><li>With the growth and adoption of REST API and frameworks that support creating a service based on REST API like <a href="https://spring.io/">Spring boot</a>, <a href="https://github.com/gin-gonic/gin">Gin</a>, <a href="https://flask.palletsprojects.com/en/2.2.x/">Flask</a>, <a href="https://rubyonrails.org/">Ruby on Rails</a>, etc., it has become much easier to develop microservices at rapid speeds.</li><li>Microservices make following <a href="https://en.wikipedia.org/wiki/Conway%27s_law">Conway’s Law</a> easier, states organizations design systems that mirror their communication structure.</li></ul><h3>Monoliths</h3><p>For the longest time, we have been using Monoliths to develop software. The monolith is commonly part of a single repository that can be run and deployed. A monolith holds all the software modules into one parent module. As the monolith grows, the modules in the monolith can have their ownership divided amongst teams.</p><h3>Pros and Cons</h3><h4>Monoliths</h4><p><strong>Pros</strong></p><ol><li>Cross-cutting changes are easier to make and test.</li><li>Complete software can be tested and released all at once.</li><li>No network latencies amongst modules since every module can be method/function calls.</li></ol><p><strong>Cons</strong></p><ol><li>With time, as monolith grows, the size of monolith deployment also increases, making deployments take much longer. This problem can be alleviated to an extent by dividing modules into services and libraries, but that also makes the deployment pipeline complex.</li><li>Code reviews in a cross-cutting change in a monolith become more challenging to review as the monolith grows.</li><li>Monolith requires a lot of dedicated tooling like:<br>- Modularized CI pipeline. Suppose there is a slight change in a specific module. In that case, the whole monolith must be built and run to test changes, which causes the CI feedback loop to be longer and makes development more complicated. The CI pipeline needs to be intelligent enough to detect modules with code changes and build only the specific modules.<br>- Bugs can be introduced quickly because of cross-cutting changes.<br>- Monitoring and alerting solutions for a monolith are complicated since the monolith is an entire system owned by the organization.</li><li>Monoliths can make it difficult for new engineers to get onboarded, as it takes time to understand the system.</li></ol><h4>Microservices</h4><p><strong>Pros</strong></p><ol><li>Microservices are individually runnable and deployable, and therefore it is much easier to create and maintain their CI/CD pipelines</li><li>The team which owns the service can dictate the deployment cadence of microservices.</li><li>Monitoring and alerting of the microservices are simplified because of independent units.</li></ol><p><strong>Cons</strong></p><ol><li>As the number of microservices grows, handling authentication and authorization across all services can become complicated.</li><li>The performance of features spanning multiple microservices can be hampered by network latency.</li><li>Testing patterns for microservices can become complicated because a change in microservice API can break flows that depend on the changed microservice.</li><li>Since microservices are independently deployable services, they can DoS one another.</li><li>The organization needs to define when it is reasonable to create a new microservice or when to add a functionality to an existing microservice.</li><li>Microservices can be expensive as each microservice can have its tech stack with its infrastructure.</li></ol><h3>So, who wins?</h3><p>Short answer; it depends.</p><p>Long answer; there is no right or wrong solution here. There’s a case to make for each implementation. Recently, there have been a lot of discussions regarding <a href="https://changelog.com/posts/monoliths-are-the-future">how monoliths will be the future</a>. Although they are known to be challenging to scale, there are solutions like <a href="https://opensource.googleblog.com/2023/03/introducing-service-weaver-framework-for-writing-distributed-applications.html">Google’s Service Weaver</a> that can help to scale monoliths.<br>On the other hand, design patterns like <a href="https://microservices.io/patterns/service-template.html">service templates</a>, <a href="https://argo-cd.readthedocs.io/en/stable/operator-manual/cluster-bootstrapping/">app of apps deployment patterns</a>, and tools like <a href="https://istio.io/latest/about/service-mesh/">service mesh</a> make scaling a fleet of microservices a lot easier.</p><p>Although there is a middle ground, <a href="http://highscalability.com/blog/2020/4/8/one-team-at-uber-is-moving-from-microservices-to-macroservic.html"><em>macro-services</em></a>. A macro-service contains modules that can be tightly coupled within the whole macro-service (modules and service) and is deployable as a single package which reduces the complexity that comes with the increased number of microservices since a macro-service can be big enough to handle complex features within itself and is small enough that the issues of a monolith do not creep in.</p><p>Continue reading <a href="https://www.anshumantripathi.com/series/samyak/">https://www.anshumantripathi.com/series/samyak/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77a8e94b6911" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>